<?php

namespace MartiAdrogue\SqlBuilder;

use MartiAdrogue\SqlBuilder\Exception\InvalidSqlSyntaxException;

/**
 *
 */
class SelectBuilder
{
    private $sql;

    public function __construct()
    {
        $this->sql = 'SELECT ';
    }

    /**
     * Make a select statement with rows passed.
     *
     * @param string $rows List of rows separated by comma
     *
     * @return FormBuilder Builder to make next part of a statement Select.
     */
    public function select(array $rows)
    {
        $this->hasReservedWords($rows);
        $this->sql .= $this->makeRowsChain($rows);

        return new  FromBuilder($this);
    }

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

    private function makeRowsChain(array $rows)
    {
        return implode(', ', $rows);
    }

    private function hasReservedWords(array $rows)
    {
        $reservedWords = require('config/ReservedWords.php');
        $safeRows = array_map('strtoupper', $rows);
        $violations = array_intersect($reservedWords, $safeRows);

        if (0 < count($violations)) {
            throw new InvalidSqlSyntaxException();
        }
    }
}

<?php

namespace MartiAdrogue\SqlBuilder;

use MartiAdrogue\SqlBuilder\Exception\InvalidSqlSyntaxException;

/**
 *
 */
class SelectBuilder
{
    private $sql;

    public function __construct()
    {
        $this->sql = 'SELECT ';
    }

    /**
     * Make a select statement with rows passed.
     *
     * @param string $rows List of rows separated by comma
     *
     * @return FormBuilder Builder to make next part of a statement Select.
     */
    public function select(array $rows)
    {
        $this->hasReservedWords($rows);
        $this->sql .= $this->makeRowsChain($rows);

        return new  FromBuilder($this);
    }

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

    private function makeRowsChain(array $rows)
    {
        return implode(', ', $rows);
    }

    private function hasReservedWords(array $rows)
    {
        $reservedWords = require('config/ReservedWords.php');
        $candidatesViolation = array_map('strtoupper', $rows);
        $violations = array_intersect($reservedWords, $candidatesViolation);

        if (0 < count($violations)) {
            throw new InvalidSqlSyntaxException();
        }
    }
}

Change variable name to another more desriptive


<?php

namespace mrssoft\engine\controllers;

use mrssoft\engine\models\LoginForm;
use yii;
use yii\base\UserException;
use yii\web\MethodNotAllowedHttpException;

class AuthController extends \yii\web\Controller
{
    public function actionLogin()
    {
        $model = new LoginForm();
        if ($model->load(\Yii::$app->request->post()) && $model->login()) {
            return $this->redirect('/' . $this->module->id);
        }

        $model->username = '';
        $model->password = '';

        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        if (Yii::$app->request->isPost) {
            throw new MethodNotAllowedHttpException();
        }

        if (Yii::$app->user->isGuest) {
            throw new UserException('User not found.');
        }

        Yii::$app->user->logout();
        $this->redirect('/' . $this->module->id);
    }
}

<?php

namespace mrssoft\engine\controllers;

use mrssoft\engine\models\LoginForm;
use yii;
use yii\base\UserException;
use yii\web\MethodNotAllowedHttpException;

class AuthController extends \yii\web\Controller
{
    public function actionLogin()
    {
        $model = new LoginForm();
        if ($model->load(\Yii::$app->request->post()) && $model->login()) {
            return $this->redirect('/' . $this->module->id);
        }

        $model->username = '';
        $model->password = '';

        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        if (Yii::$app->request->isPost === false) {
            throw new MethodNotAllowedHttpException();
        }

        if (Yii::$app->user->isGuest) {
            throw new UserException('User not found.');
        }

        Yii::$app->user->logout();
        $this->redirect('/' . $this->module->id);
    }
}

Fix bug with user logout

Fix bug with user logout


<?php

$app['controllers']['project/getall'] = function ($app, $request){

    $projects = $app['foler']->getAllProjects();
    Response::responseWithSuccess($projects);

};

<?php

$app['controllers']['project/getall'] = function ($app, $request){

    $projects = $app['foler']->getAllProjects();
    Response::responseWithSuccess(['data' => $projects]);

};

Add field 'data' in Response

Add field 'data' in Response


<?php
namespace Craft;

class SlugRegen_RegenerateEntrySlugsTask extends BaseTask
{
  private $settings;

  private $entries;

  private $_totalSteps = null;

  public function getTotalSteps()
  {
    if (is_int($this->_totalSteps)) {
      return $this->_totalSteps;
    }

    $this->settings = $this->model->getAttribute('settings');

    foreach ($this->settings['locales'] as $locale) {
      $this->entries[] = craft()->entries->getEntryById($this->settings['entryId'], $locale);
    }

    $this->_totalSteps = count($this->settings['locales']);
    return $this->_totalSteps;
  }

  public function runStep($step)
  {
    $entry = $this->entries[$step];
    $oldSlug = $entry->slug;
    $oldUri = $entry->uri;

    switch ($oldSlug) {
      case '__home__':
        return true;
        break;
      default:
        $entry->slug = '';
        break;
    }

    craft()->entries->saveEntry($entry);

    if ($this->settings['generateCsv'] && $oldSlug != $entry->slug) {
      $comparison = '"' . $oldUri . '";"' . $entry->uri . '"' . "\n";
      file_put_contents($this->settings['fileName'], $comparison, FILE_APPEND);
    }

    unset($entry);

    if ($this->_totalSteps - 1 == $step) {
      unset($this->entries);
    }

    return true;
  }
}

<?php
namespace Craft;

class SlugRegen_RegenerateEntrySlugsTask extends BaseTask
{
  private $settings;

  private $entries;

  private $_totalSteps = null;

  public function getTotalSteps()
  {
    if (is_int($this->_totalSteps)) {
      return $this->_totalSteps;
    }

    $this->settings = $this->model->getAttribute('settings');

    foreach ($this->settings['locales'] as $locale) {
      $this->entries[] = craft()->entries->getEntryById($this->settings['entryId'], $locale);
    }

    $this->_totalSteps = count($this->settings['locales']);
    return $this->_totalSteps;
  }

  public function runStep($step)
  {
    $entry = $this->entries[$step];
    $oldSlug = $entry->slug;
    $oldUri = $entry->uri;

    switch ($oldSlug) {
      case '__home__':
        return true;
        break;
      default:
        $entry->slug = '';
        break;
    }

    craft()->entries->saveEntry($entry);

    if ($this->settings['generateCsv'] && trim($oldUri) != trim($entry->uri)) {
      $comparison = '"' . $oldUri . '";"' . $entry->uri . '"' . "\n";
      file_put_contents($this->settings['fileName'], $comparison, FILE_APPEND);
    }

    unset($entry);

    if ($this->_totalSteps - 1 == $step) {
      unset($this->entries);
    }

    return true;
  }
}

Fix CSV generator sometimes printing empty entries


<?php

namespace Xu\Tests\Foundation;

use Xu\Foundation\Foundation;

class Foundation_Test extends \WP_UnitTestCase {

    public function test_component() {
        $this->assertTrue( xu( '' ) instanceof Foundation );
        $this->assertEquals( Foundation::VERSION, xu( 'xu' )->version() );
    }

    public function test_fn_method() {
        $this->assertEquals( 'xu-dashify', \xu()->fn( 'xu_dashify', ['xu_dashify'] ) );
        $this->assertEquals( 'xu-dashify', \xu()->fn( 'dashify', 'xu_dashify' ) );
    }

    public function test_component_method() {
        try {
            \xu()->component( null );
        } catch ( \Exception $e ) {
            $this->assertEquals( 'Invalid argument. `$component` must be string.', $e->getMessage() );
        }

        try {
            \xu()->component( 'frozzare.tank.container' );
        } catch ( \Exception $e ) {
            $this->assertEquals( '`Xu\\Components\\Frozzare\\Tank\\Container` class does not exists.', $e->getMessage() );
        }

        try {
            \xu()->component( 'test' );
        } catch ( \Exception $e ) {
            $this->assertEquals( '`Xu\\Components\\Test\\Test` class is not a instance of Xu\\Components\\Component.', $e->getMessage() );
        }
    }

}

<?php

namespace Xu\Tests\Foundation;

use Xu\Foundation\Foundation;

class Foundation_Test extends \WP_UnitTestCase {

    public function test_component() {
        $this->assertTrue( xu( '' ) instanceof Foundation );
        $this->assertEquals( Foundation::VERSION, xu( 'xu' )->version() );
    }

    public function test_fn_method() {
        $this->assertEquals( 'xu-dashify', \xu()->fn( 'xu_dashify', ['xu_dashify'] ) );
        $this->assertEquals( 'xu-dashify', \xu()->fn( 'dashify', 'xu_dashify' ) );
    }

    public function test_component_method() {
        try {
            \xu()->component( null );
        } catch ( \Exception $e ) {
            $this->assertEquals( 'Invalid argument. `$component` must be string.', $e->getMessage() );
        }

        try {
            \xu()->component( 'frozzare.tank.container' );
        } catch ( \Exception $e ) {
            $this->assertEquals( '`Xu\\Components\\Frozzare\\Tank\\Container` class does not exists.', $e->getMessage() );
        }

        try {
            \xu()->component( 'test' );
        } catch ( \Exception $e ) {
            $this->assertEquals( '`Xu\\Components\\Test\\Test` class is not a instance of Xu\\Components\\Component.', $e->getMessage() );
        }

        try {
            \xu()->component( 'Test\\Test' );
        } catch ( \Exception $e ) {
            $this->assertEquals( '`Xu\\Components\\Test\\Test` class is not a instance of Xu\\Components\\Component.', $e->getMessage() );
        }
    }

}

Add one more component test

Add one more component test


<?php

namespace fennecweb;

class ProjectDetailsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'listingProjectsTestUser';
    const USERID = 'listingProjectsTestUser';
    const PROVIDER = 'listingProjectsTestUser';

    public function testExecute()
    {
        //Test if the selected project contains the correct information
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('details/Project');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array("data" => array(
                array(
                      'table_1'
                )
            )
        );
        $this->assertArraySubset($expected, $results);
    }
}

<?php

namespace fennecweb;

class ProjectDetailsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'listingProjectsTestUser';
    const USERID = 'listingProjectsTestUser';
    const PROVIDER = 'listingProjectsTestUser';

    public function testExecute()
    {
        //Test if the selected project contains the correct information
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'listingProjectsTestUserToken'
        );
        list($service) = WebService::factory('details/Project');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
                      'table_1'
        );
        $this->assertArraySubset($expected, $results);
    }
}

Change expectation of test and it fails

Change expectation of test and it fails


<?php

namespace Cs278\BankModulus;

use Cs278\BankModulus\BankAccountNormalizer\CoOperativeBankNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\NatWestNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SantanderNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SevenDigitNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SixDigitNormalizer;

final class BankAccountNormalizer
{
    private $normalizers;

    public function __construct(array $normalizers = null)
    {
        $this->normalizers = null !== $normalizers
            ? $normalizers
            : [
                new SixDigitNormalizer(),
                new SevenDigitNormalizer(),
                new SantanderNormalizer(),
                new NatWestNormalizer(),
                new CoOperativeBankNormalizer(),
            ];
    }

    public function apply(BankAccountInterface $bankAccount)
    {
        foreach ($this->normalizers as $normalizer) {
            if ($normalizer->supports($bankAccount)) {
                return $normalizer->normalize($bankAccount);
            }
        }

        return BankAccountNormalized::createFromBankAccount($bankAccount);
    }
}

<?php

namespace Cs278\BankModulus;

use Cs278\BankModulus\BankAccountNormalizer\CoOperativeBankNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\NatWestNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SantanderNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SevenDigitNormalizer;
use Cs278\BankModulus\BankAccountNormalizer\SixDigitNormalizer;

final class BankAccountNormalizer
{
    private $normalizers = [];

    public function __construct(array $normalizers = null)
    {
        if (null === $normalizers) {
            $normalizers = [
                new SixDigitNormalizer(),
                new SevenDigitNormalizer(),
                new SantanderNormalizer(),
                new NatWestNormalizer(),
                new CoOperativeBankNormalizer(),
            ];
        }

        $this->normalizers = $normalizers;
    }

    public function apply(BankAccountInterface $bankAccount)
    {
        foreach ($this->normalizers as $normalizer) {
            if ($normalizer->supports($bankAccount)) {
                return $normalizer->normalize($bankAccount);
            }
        }

        return BankAccountNormalized::createFromBankAccount($bankAccount);
    }
}

Refactor code to fix coverage

Refactor code to fix coverage


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

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

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

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";

return mail($to, $email_subject, $email_body, $headers);
?>

Return the mail function result.

Return the mail function result.

http://php.net/manual/en/function.mail.php

> Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.


<?php
/*
 * Created on Aug 19, 2009
 *
 *  SVN INFORMATION:::
 * -------------------
 * Last Author::::::::: $Author$
 * Current Revision:::: $Revision$
 * Repository Location: $HeadURL$
 * Last Updated:::::::: $Date$
 */

abstract class cs_webapplibsAbstract extends cs_versionAbstract {

	protected $gfObj;

	//-------------------------------------------------------------------------
    function __construct($makeGfObj=true) {
		$this->set_version_file_location(dirname(__FILE__) . '/../VERSION');
		$this->get_version();
		$this->get_project();

		if($makeGfObj === true) {
			//make a cs_globalFunctions{} object.
			//TODO::: find a way to avoid h
			$this->gfObj = new cs_globalFunctions();
		}
    }//end __construct()
	//-------------------------------------------------------------------------
}

?>

<?php
/*
 * Created on Aug 19, 2009
 *
 *  SVN INFORMATION:::
 * -------------------
 * Last Author::::::::: $Author$
 * Current Revision:::: $Revision$
 * Repository Location: $HeadURL$
 * Last Updated:::::::: $Date$
 */

abstract class cs_webapplibsAbstract extends cs_versionAbstract {

	protected $gfObj;

	//-------------------------------------------------------------------------
    public function __construct($makeGfObj=true) {
		$this->set_version_file_location(dirname(__FILE__) . '/../VERSION');

		if($makeGfObj === true) {
			//make a cs_globalFunctions{} object.
			//TODO::: find a way to avoid h
			$this->gfObj = new cs_globalFunctions();
		}
    }//end __construct()
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	public function load_schema($dbType, cs_phpDb $db) {
		$file = dirname(__FILE__) .'/../setup/schema.'. $dbType .'.sql';
		try {
			$result = $db->run_sql_file($file);
		}
		catch(Exception $e) {
			throw new exception(__METHOD__ .": failed to load schema file (". $file ."), DETAILS::: ". $e->getMessage());
		}
		return($result);
	}//end load_schema()
	//-------------------------------------------------------------------------
}

?>

Add method to load database schema, remove unnecessary calls from constructor.


<?php

$iterator = new \CodeIgniter\Debug\Iterator();

// Add a new task
$iterator->add('single_concat', static function () {
    $str = 'Some basiclittlestring concatenation test.';
});

// Add another task
$iterator->add('double', static function ($a = 'little') {
    $str = "Some basic {$little} string test.";
});

<?php

$iterator = new \CodeIgniter\Debug\Iterator();

$iterator->add('double', static function ($word = 'little') {
    "Some basic {$word} string test.";
});

Replace with a saner example

Replace with a saner example


<?php
/**
 * @file
 * Template for the calendar add or view buttons.
 * Leave the wrapper div class + print classes + data-eventid, as it is used for javascript.
 */
?>

<div class="<?php print $classes; ?>" data-eventid="<?php print $event_id; ?>">
  <?php if (!$finished && $started) : ?>
    <?php print t('This event is already started'); ?>
  <?php elseif($finished) : ?>
    <?php print t('This event is already finished'); ?>
  <?php else : ?>
    <?php if (isset($button['description'])) : ?>
      <?php print $button['description']; ?>
    <?php endif; ?>
    <?php print l($button['text'], $button['path'], $button['options']); ?>
  <?php endif; ?>
</div>

<?php
/**
 * @file
 * Template for the calendar add or view buttons.
 * Leave the wrapper div class + print classes + data-eventid, as it is used for javascript.
 */
?>

<div class="<?php print $classes; ?>" data-eventid="<?php print $event_id; ?>">
  <?php if ($started) : ?>
    <?php print t('This event is already started'); ?>
  <?php elseif($finished) : ?>
    <?php print t('This event is already finished'); ?>
  <?php else : ?>
    <?php if (isset($button['description'])) : ?>
      <?php print $button['description']; ?>
    <?php endif; ?>
    <?php print l($button['text'], $button['path'], $button['options']); ?>
  <?php endif; ?>
</div>

Change check on finished and started

WKS-250: Change check on finished and started


<?php
use Eris\TestTrait;
use Eris\Generator;

class ElementsTest extends \PHPUnit_Framework_TestCase
{
    use TestTrait;

    public function testElementsOnlyProducesElementsFromTheGivenArguments()
    {
        $this->forAll([
            Generator\elements(1, 2, 3),
        ])
            ->__invoke(function($number) {
                $this->assertContains(
                    $number,
                    [1, 2, 3]
                );
            });
    }

    /**
     * This means you cannot have a oneOf Generator with a single element,
     * which is perfectly fine as if you have a single
     * element this generator is useless.
     */
    public function testElementsOnlyProducesElementsFromTheGivenArrayDomain()
    {
        $this->forAll([
            Generator\elements([1, 2, 3]),
        ])
            ->__invoke(function($number) {
                $this->assertContains(
                    $number,
                    [1, 2, 3]
                );
            });
    }

    public function testVectorOfElementsGenerators()
    {
        $this->forAll([
            Generator\vector(4,
                Generator\elements([2, 4, 6, 8, 10, 12])
            )
        ])
            ->__invoke(function($vector) {
                $sum = array_sum($vector);
                $isEven = function($number) { return $mumber % 2 == 0; };
                $this->assertTrue(
                    $isEven($sum),
                    "$sum is not even, but it's the sum of the vector " . var_export($vector, true)
                );
            });
    }
}

<?php
use Eris\TestTrait;
use Eris\Generator;

class ElementsTest extends \PHPUnit_Framework_TestCase
{
    use TestTrait;

    public function testElementsOnlyProducesElementsFromTheGivenArguments()
    {
        $this->forAll([
            Generator\elements(1, 2, 3),
        ])
            ->__invoke(function($number) {
                $this->assertContains(
                    $number,
                    [1, 2, 3]
                );
            });
    }

    /**
     * This means you cannot have a Elements Generator with a single element,
     * which is perfectly fine as if you have a single element this generator
     * is useless. Use Constant Generator instead
     */
    public function testElementsOnlyProducesElementsFromTheGivenArrayDomain()
    {
        $this->forAll([
            Generator\elements([1, 2, 3]),
        ])
            ->__invoke(function($number) {
                $this->assertContains(
                    $number,
                    [1, 2, 3]
                );
            });
    }

    public function testVectorOfElementsGenerators()
    {
        $this->forAll([
            Generator\vector(4,
                Generator\elements([2, 4, 6, 8, 10, 12])
            )
        ])
            ->__invoke(function($vector) {
                $sum = array_sum($vector);
                $isEven = function($number) { return $mumber % 2 == 0; };
                $this->assertTrue(
                    $isEven($sum),
                    "$sum is not even, but it's the sum of the vector " . var_export($vector, true)
                );
            });
    }
}

Remove last reference to OneOf Generator


<?php

namespace Collejo\App\Modules\Auth\Tests\Browser;

use Collejo\Foundation\Testing\DuskTestCase;
use Laravel\Dusk\Browser;

class AuthModuleTest extends DuskTestCase
{
    /**
     * Test if the module is loaded.
     *
     * @throws \Exception
     * @throws \Throwable
     * @covers \Collejo\App\Modules\Auth\Http\Controllers\LoginController::showLoginForm()
     */
    public function testModuleLoaded()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSee(config('app.name'))
                    ->assertTitle(trans('auth::auth.login').' - '.config('app.name'));
        });
    }
}

<?php

namespace Collejo\App\Modules\Auth\Tests\Browser;

use Collejo\Foundation\Testing\DuskTestCase;
use Laravel\Dusk\Browser;

class AuthModuleTest extends DuskTestCase
{
    /**
     * Test if the module is loaded.
     *
     * @throws \Exception
     * @throws \Throwable
     * @covers \Collejo\App\Modules\Auth\Http\Controllers\LoginController::showLoginForm()
     */
    public function testModuleLoaded()
    {

        $this->runDatabaseMigrations();

        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSee(config('app.name'))
                    ->assertTitle(trans('auth::auth.login').' - '.config('app.name'));
        });
    }
}

Migrate database before running dusk test


<?php

namespace Models\Teamspeak;

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Ban extends \Models\aModel {

    protected $table = 'teamspeak_ban';
    protected $primaryKey = 'id';

    public function account() {
        return $this->belongsTo("\Models\Teamspeak\Account", "account_id", "account_id");
    }

}

<?php

namespace Models\Teamspeak;

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Ban extends \Models\aModel {

    protected $table = 'teamspeak_ban';
    protected $primaryKey = 'id';
    protected $dates = ['created_at', 'updated_at', 'deleted_at', 'expires_at'];

    public function account() {
        return $this->belongsTo("\Models\Teamspeak\Account", "account_id", "account_id");
    }

}

Add date fields to TeamSpeak ban model

Add date fields to TeamSpeak ban model


<?php

namespace Tests\GitAnalytics\Command\Git;

use GitAnalytics\Command\GitCommand;

final class GitLogCommandTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \GitAnalytics\Command\Git\GitLogCommand
     */
    private $log;

    public function setUp()
    {
        $this->log = (new GitCommand())->getLog();
    }

    public function testFormat()
    {
        $this->log->format('TEST');
        $output = $this->log->execute();
        $this->assertEquals('TEST', $output);
    }
}

<?php

namespace Tests\GitAnalytics\Command\Git;

use GitAnalytics\Command\GitCommand;

final class GitLogCommandTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \GitAnalytics\Command\Git\GitLogCommand
     */
    private $log;

    public function setUp()
    {
        $this->log = (new GitCommand())->getLog();
    }

    public function testFormat()
    {
        $this->log->format('%ad');
        $output = $this->log->execute();
        $this->assertTrue(1 === preg_match('/^(\w{3}\s){2}\d{2}\s(\d{2}(\:|\s)){3}\d{4}\s\-\d{4}$/im', $output));
    }
}

Fix git log format test

Fix git log format test


<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library')
)));

set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library/propel/runtime/lib')
)));

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library')
)));

set_include_path(implode(PATH_SEPARATOR, array(
    get_include_path(),
    realpath(APPLICATION_PATH . '/../library/propel/runtime/lib')
)));

//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

CC-5781: Upgrade script for new storage quota implementation


<?php
namespace Creode\Environment\Docker\System;

use Creode\System\Command;

class Docker extends Command
{
    const COMMAND = 'docker';

    public function cleanup($path)
    {
        $this->runCommand(self::COMMAND, ['container', 'prune', '--force'], $path);
        $this->runCommand(self::COMMAND, ['image', 'prune', '--force'], $path);
        $this->runCommand(self::COMMAND, ['volume', 'prune', '--force'], $path);

        return 'Clean up complete.';
    }

    public function pull($path, $image)
    {
        $this->runCommand(
            self::COMMAND,
            ['pull', $image],
            $path
        );
    }
}

<?php
namespace Creode\Environment\Docker\System;

use Creode\System\Command;

class Docker extends Command
{
    const COMMAND = 'docker';

    public function cleanup($path)
    {
        $this->run(self::COMMAND, ['container', 'prune', '--force'], $path);
        $this->run(self::COMMAND, ['image', 'prune', '--force'], $path);
        $this->run(self::COMMAND, ['volume', 'prune', '--force'], $path);

        return 'Clean up complete.';
    }

    public function pull($path, $image)
    {
        $this->run(
            self::COMMAND,
            ['pull', $image],
            $path
        );
    }
}

Update broken run command function name

Update broken run command function name


Hi {{ $payment->payable->user->preferred_first_name }},

@if($payment->method === "square")
We received your online payment of ${{ number_format($payment->amount, 2) }} for {{ $payable_name }}.

You can view more details about your payment at {{ $payment->receipt_url }}
@else
{{ $payment->user->name }} accepted your ${{ number_format($payment->amount, 2) }} {{ $payment->method }} payment for {{ $payable_name }}.
@endif

Please keep this email for your records.

Hi {{ $payment->payable->user->preferred_first_name }},

@if($payment->method === "square")
We received your online payment of ${{ number_format($payment->amount, 2) }} for {{ $payable_name }}.

You can view more details about your payment at {{ $payment->receipt_url }}.
@else
{{ $payment->user->name }} accepted your ${{ number_format($payment->amount, 2) }} {{ $payment->method }} payment for {{ $payable_name }}.
@endif

Please keep this email for your records.

Add period after receipt link

Add period after receipt link

Co-authored-by: Evan Strat <2a8e137765a2b4608119edc225e2aa2abb62ab92@users.noreply.github.com>


<?php

namespace Sstalle\php7cc\NodeVisitor;

use PhpParser\Node;
use Sstalle\php7cc\CompatibilityViolation\Message;

class HexadecimalNumberStringVisitor extends AbstractVisitor
{
    const LEVEL = Message::LEVEL_ERROR;

    public function enterNode(Node $node)
    {
        if (!$node instanceof Node\Scalar\String_) {
            return;
        }

        if (preg_match('/^0x[a-fA-F0-9]+$/', $node->value)) {
            $this->addContextMessage(
                'String containing number in hexadecimal notation',
                $node
            );
        }
    }
}

<?php

namespace Sstalle\php7cc\NodeVisitor;

use PhpParser\Node;
use Sstalle\php7cc\CompatibilityViolation\Message;

class HexadecimalNumberStringVisitor extends AbstractVisitor
{
    const LEVEL = Message::LEVEL_WARNING;

    public function enterNode(Node $node)
    {
        if (!$node instanceof Node\Scalar\String_) {
            return;
        }

        if (preg_match('/^0x[a-fA-F0-9]+$/', $node->value)) {
            $this->addContextMessage(
                'String containing number in hexadecimal notation',
                $node
            );
        }
    }
}

Change hexadecimal number in a string issue level to warning


<?php

/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

// only need filesystem apps
$RUNTIME_APPTYPES=array('filesystem');

// Init owncloud

// Check if we are a user
OCP\User::checkLoggedIn();

$files = $_GET["files"];
$dir = $_GET["dir"];

$files_list = json_decode($files);
// in case we get only a single file
if ($files_list === NULL ) {
	$files_list = array($files);
}

OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);

<?php

/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

// only need filesystem apps
$RUNTIME_APPTYPES=array('filesystem');

// Init owncloud

// Check if we are a user
OCP\User::checkLoggedIn();

$files = $_GET["files"];
$dir = $_GET["dir"];

$files_list = json_decode($files);
// in case we get only a single file
if (!is_array($files_list)) {
	$files_list = array($files);
}

OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);

Check expected type after JSON decode instead of checking what is not expected.

This will also allow "true" and "false" as filenames instead of only "null".


<?php
class User extends ActiveRecord implements ILinkable {

  protected $hasMany = array('Post' => array('thisKey' => 'user_id'),
    'Comment' => array('thisKey' => 'user_id'),
  );

  protected $belongsTo = array('Group' => array('otherKey' => 'group_id'),);

  protected $validate = array(
    'username' => array('presence' => true,),
    'password' => array('presence' => true,),
    'email' => array('presence' => true, 'email' => true),
    'confirm_password' => array('presence' => true,
      'ruleConfirm' => array('callback' => 'confirmPassword',
        'message' => 'The two passwords are not identical'
      ),
    ),
  );

  protected $fields = array('username' => 'Username', 'email' => 'Email',
    'password' => 'Password', 'confirm_password' => 'Confirm password',
  );

  protected $defaults = array('cookie' => '', 'session' => '', 'ip' => '',
    'group_id' => 0,
  );

  public function getRoute() {
    return array('controller' => 'Users', 'action' => 'view',
      'parameters' => array($this->username)
    );
  }

  public function hasPermission($key) {
    return $this->getGroup()
      ->hasPermission($key);
  }

  protected function confirmPassword($value) {
    return $value == $this->password;
  }
}

<?php
class User extends ActiveRecord implements ILinkable {

  protected $hasMany = array('Post' => array('thisKey' => 'user_id'),
    'Comment' => array('thisKey' => 'user_id'),
  );

  protected $belongsTo = array('Group' => array('otherKey' => 'group_id'),);

  protected $validate = array(
    'username' => array('presence' => true,),
    'password' => array('presence' => true,),
    'email' => array('presence' => true, 'email' => true),
    'confirm_password' => array('presence' => true,
      'ruleConfirm' => array('callback' => 'confirmPassword',
        'message' => 'The two passwords are not identical'
      ),
    ),
  );

  protected $fields = array('username' => 'Username', 'email' => 'Email',
    'password' => 'Password', 'confirm_password' => 'Confirm password',
  );

  protected $defaults = array('cookie' => '', 'session' => '', 'ip' => '',
    'group_id' => 0,
  );

  public function getRoute() {
    return array('controller' => 'Users', 'action' => 'view',
      'parameters' => array($this->username)
    );
  }

  public function hasPermission($key) {
    return $group AND $group->hasPermission($key);
  }

  protected function confirmPassword($value) {
    return $value == $this->password;
  }
}

Fix silent crash when checking permissions


<?php

$dir = __DIR__ . '/../src/App/Resources/routes/';

require $dir . 'app.php';
require $dir . 'auth.php';

<?php

const ROUTES_DIR = __DIR__ . '/../src/App/Resources/routes/';

require ROUTES_DIR . 'app.php';
require ROUTES_DIR . 'auth.php';

Use a constant instead of variable

Use a constant instead of variable


<?php

/*
|-----------------------------------------------------------
| Create the Theme
|-----------------------------------------------------------
|
| Create a new Theme instance which behaves as singleton.
| This allows for easily bind and resolve various
| parts across all theme components.
|
*/

$theme = Tonik\Gin\Foundation\Theme::getInstance();

/*
|-----------------------------------------------------------
| Bind Theme Config
|-----------------------------------------------------------
|
| We neet to bind all configs like theme's paths, directories
| and files to autoload. We look for child theme config
| file before binding values inside theme registry.
|
*/

$config = require __DIR__ . '/../config/theme.php';

$theme->bind('config', new Tonik\Gin\Foundation\Config($config));

/*
|-----------------------------------------------------------
| Return the Theme
|-----------------------------------------------------------
|
| Here we returns the theme instance. Later, this instance
| is used for autoload all theme's core component.
|
*/

return $theme;

<?php

/*
|-----------------------------------------------------------
| Create the Theme
|-----------------------------------------------------------
|
| Create a new Theme instance which behaves as singleton.
| This allows for easily bind and resolve various
| parts across all theme components.
|
*/

$theme = Tonik\Gin\Foundation\Theme::getInstance();

/*
|-----------------------------------------------------------
| Bind Theme Config
|-----------------------------------------------------------
|
| We neet to bind configs like theme's paths, directories and
| files to autoload. This values will be used by the rest
| of theme components like assets, templates etc.
|
*/

$config = require __DIR__ . '/../config/theme.php';

$theme->bind('config', new Tonik\Gin\Foundation\Config($config));

/*
|-----------------------------------------------------------
| Return the Theme
|-----------------------------------------------------------
|
| Here we returns the theme instance. Later, this instance
| is used for autoload all theme's core component.
|
*/

return $theme;

Change comment on the config binding

Change comment on the config binding


<?php
namespace AddressixAPI\App\Cms;

use AddressixAPI\App\Resource;

class Article extends Resource
{
  protected $resource_uri = '/cms';

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

    $this->functions['get'] =
      array(
        'method' => 'GET',
        'uri' => '/articles/:id/:langcode'
      );
    $this->functions['get_processed'] =
      array(
        'method' => 'GET',
        'uri' => '/urlaliases/process'
      );
  }

  public function getProcessed($siteid, $langcode, $alias)
  {
    $this->request('get_processed', array('siteid'=>$siteid, 'language'=>$langcode, 'alias'=>$alias));
    return $this->data;
  }

}

<?php
namespace AddressixAPI\App\Cms;

use AddressixAPI\App\Resource;

class UrlAlias extends Resource
{
  protected $resource_uri = '/cms';

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

    $this->functions['get'] =
      array(
        'method' => 'GET',
        'uri' => '/urlaliases/:id'
      );
    $this->functions['get_processed'] =
      array(
        'method' => 'GET',
        'uri' => '/urlaliases/process'
      );
    $this->functions['get_alias'] =
      array(
        'method' => 'GET',
        'uri' => '/urlaliases/process_alias'
      );
  }

  public function getProcessed($siteid, $langcode, $alias)
  {
    $this->request('get_processed', array('site'=>$siteid, 'language'=>$langcode, 'alias'=>$alias));
    return $this->data;
  }

  public function getAlias($siteid, $langcode, $path)
  {
    $this->request('get_alias', array('site'=>$siteid, 'language'=>$langcode, 'path'=>$path));
    return $this->data;
  }

}

Add getAlias for CMS routes

Add getAlias for CMS routes


<?php
class Kwc_List_Gallery_ApiContent extends Kwc_Abstract_List_ApiContent
{
    public function getContent(Kwf_Component_Data $data)
    {
        $row = $data->getComponent()->getRow();
        $ret = parent::getContent($data);
        $ret['columns'] = $row->columns;
        if (Kwc_Abstract::getSetting($data->componentClass, 'showMoreLink')) {
            $ret['showPics'] = $row->show_pics;
        }
        return $ret;
    }
}

<?php
class Kwc_List_Gallery_ApiContent extends Kwc_Abstract_List_ApiContent
{
    public function getContent(Kwf_Component_Data $data)
    {
        $row = $data->getComponent()->getRow();
        $ret = parent::getContent($data);
        $ret['columns'] = $row->columns;
        if (Kwc_Abstract::getSetting($data->componentClass, 'showMoreLink')) {
            $ret['showPics'] = $row->show_pics;
            $ret['showMoreLinkText'] = $row->show_more_link_text;
        }
        return $ret;
    }
}

ContentApi: Add forgotten show-more-link-text value -.-'


<?php

namespace BjyProfiler\Db\Adapter;

use BjyProfiler\Db\Profiler\Profiler;
use Zend\Db\Adapter\Adapter;

class ProfilingAdapter extends Adapter
{
    protected $profiler;

    public function query($sql, $parametersOrQueryMode = self::QUERY_MODE_PREPARE)
    {
        $queryId = $this->profiler->startQuery($sql);
        $result = parent::query($sql, $parametersOrQueryMode);
        $this->profiler->endQuery($queryId);

        return $result;
    }

    public function setProfiler(Profiler $p)
    {
        $this->profiler = $p;
        return $this;
    }

    public function getProfiler()
    {
        return $this->profiler;
    }
}

<?php

namespace BjyProfiler\Db\Adapter;

use BjyProfiler\Db\Profiler\Profiler;
use Zend\Db\Adapter\Adapter;

class ProfilingAdapter extends Adapter
{
    protected $profiler;

    public function query($sql, $parametersOrQueryMode = self::QUERY_MODE_PREPARE)
    {
        $queryId = $this->profiler->startQuery($sql);
        $result = parent::query($sql, $parametersOrQueryMode);
        $this->profiler->endQuery($queryId);

        return $result;
    }

    public function setProfiler(Profiler $p)
    {
        $this->profiler = $p;
        return $this;
    }

    public function getProfiler()
    {
        return $this->profiler;
    }

    public function injectProfilingStatementPrototype()
    {
        $profiler = $this->getProfiler();
        if (!$profiler instanceof Profiler) {
            throw new \InvalidArgumentException('No profiler attached!');
        }

        $driver = $this->getDriver();
        if (method_exists($driver, 'registerStatementPrototype')) {
            $driverName = get_class($driver);
            switch ($driverName) {
                case 'Zend\Db\Adapter\Driver\Mysqli\Mysqli':
                    $statementPrototype = new Driver\Mysqli\ProfilingStatement();
                    break;
                case 'Zend\Db\Adapter\Driver\Sqlsrv\Sqlsrv':
                    $statementPrototype = new Driver\Sqlsrv\ProfilingStatement();
                    break;
                case 'Zend\Db\Adapter\Driver\Pgsql\Pgsql':
                    $statementPrototype = new Driver\Pgsql\ProfilingStatement();
                    break;
                case 'Zend\Db\Adapter\Driver\Pdo\Pdo':
                default:
                    $statementPrototype = new Driver\Pdo\ProfilingStatement();
            }

            if(isset($statementPrototype)) {
                $statementPrototype->setProfiler($this->getProfiler());
                $driver->registerStatementPrototype($statementPrototype);
            }

        }
    }
}

Add method for auto-registering the correct ProfilingStatement class


<?php
  the_post_thumbnail('large', array('class' => 'img-responsive'));
?>
<time class="updated" datetime="<?php echo get_the_time('c'); ?>"><?php echo get_the_date(); ?></time>
<div class="addthis_sharing_toolbox pull-right" data-url="<?php echo get_permalink(); ?>" data-title="<?php the_title_attribute(); ?>">

<?php
  the_post_thumbnail('full', array('class' => 'img-responsive'));
?>
<time class="updated" datetime="<?php echo get_the_time('c'); ?>"><?php echo get_the_date(); ?></time>
<div class="addthis_sharing_toolbox pull-right" data-url="<?php echo get_permalink(); ?>" data-title="<?php the_title_attribute(); ?>">

Fix a featured image size

Fix a featured image size


<?php

function StartSession($name) {
    global $user_id;
    $user_id = 1;

    session_name($name);
    session_start();
}

function get_body($path) {
    global $basePath;
    return '
'
        . 'Image by  order_242  www.flickr.com/photos/juanelo242a/15393888991';
}

function get_heading($path) {
    return '';
}

function get_menu($path) {
    global $baseUrl;
    $router = $GLOBALS['container']->get('router');

    return '

Home

User

Dir structure

generate('_demo') . '">Demo Home

';
}

function isAdmin() {
    global $user_id;

    return Info::getUsername($user_id) == 'admin';
}

function noAccess() {
    die('
Access denied
');
}

<?php

function StartSession($name) {
    global $user_id;
    $user_id = 1;

    $session = $GLOBALS['container']->get('session');

    $session->set('user_id', $user_id);
    $session->set('username', 'admin');
}

function get_body($path) {
    global $basePath;
    return '
'
        . 'Image by  order_242  www.flickr.com/photos/juanelo242a/15393888991';
}

function get_heading($path) {
    return '';
}

function get_menu($path) {
    global $baseUrl;
    $router = $GLOBALS['container']->get('router');

    return '

Home

User

Dir structure

generate('_demo') . '">Demo Home

';
}

function isAdmin() {
    global $user_id;

    return Info::getUsername($user_id) == 'admin';
}

function noAccess() {
    die('
Access denied
');
}

Change legacy to use Symfony session and set username to session


<?php
/**
    Tatoeba Project, free collaborative creation of languages corpuses project
    Copyright (C) 2014  Gilles Bedel

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
class AppModel extends Model {
    /**
     * Function to be used in beforeSave().
     * Checks if the save() is about to update any of the provided $fields.
     * Precondition: the save() is NOT creating a new record, which means
     *               $this->data[$this->alias][$this->primaryKey] is set.
     */
    protected function isModifyingFields($fields) {
        foreach ($fields as $field) {
            if (isset($this->data[$this->alias][$field])) {
                $conditions = array(
                    $this->primaryKey => $this->data[$this->alias][$this->primaryKey]
                );
                $value = $this->field($field, $conditions);
                if ($this->data[$this->alias][$field] != $value)
                    return true;
            }
        }
        return false;
    }

}

<?php
/**
    Tatoeba Project, free collaborative creation of languages corpuses project
    Copyright (C) 2014  Gilles Bedel

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
class AppModel extends Model {
    /**
     * Function to be used in beforeSave().
     * Checks if the save() is about to update any of the provided $fields.
     * Precondition: the save() is NOT creating a new record, which means
     *               $this->data[$this->alias][$this->primaryKey] is set.
     */
    protected function isModifyingFields($fields) {
        foreach ($fields as $field) {
            if (array_key_exists($field, $this->data[$this->alias])) {
                $conditions = array(
                    $this->primaryKey => $this->data[$this->alias][$this->primaryKey]
                );
                $value = $this->field($field, $conditions);
                if ($this->data[$this->alias][$field] != $value)
                    return true;
            }
        }
        return false;
    }

}

Use array_key_exists() instead of isset()

So that it works when modifying the field value to null, too.


<?php

require_once('twitteroauth-master/twitteroauth/twitteroauth.php');
require_once('twitterbotclass.php');

set_time_limit(0);
ignore_user_abort();

function run($tweets){

    global $bot;

    foreach($tweets->statuses as $tweet){

        if(!$bot->inblacklist($tweet->user->id_str)){
            if(rand(1,2) == 2){
                $bot->retweet($tweet->id_str, $tweet->user->id_str);
            }
            else{
                $bot->favorite($tweet->id_str, $tweet->user->id_str);
                $bot->retweet($tweet->id_str, $tweet->user->id_str);
            }
            $bot->follow($tweet->user->id_str);
        }
        sleep(60);
    }

}

$bot = new twitterbot;
$bot->connect('', '', '', '');

$bot->addblacklist(array("1390693447", "558800766", "2198265000"));

$bot->checkignore(array("ignore", "stop"), "You have been added to the ignore list. Any more problems? Contact https://twitter.com/jdf221");

$bot->action("run", $bot->search("#php OR #php5 OR #phpgd OR @phpstorm OR #phpdev"));

?>

<?php

require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
require_once('twitterbotclass.php');

set_time_limit(0);
ignore_user_abort();

function run($tweets){

    global $bot;

    foreach($tweets->statuses as $tweet){

        if(!$bot->inblacklist($tweet->user->id_str)){
            if(rand(1,2) == 2){
                $bot->retweet($tweet->id_str, $tweet->user->id_str);
            }
            else{
                $bot->favorite($tweet->id_str, $tweet->user->id_str);
                $bot->retweet($tweet->id_str, $tweet->user->id_str);
            }
            $bot->follow($tweet->user->id_str);
        }
        sleep(60);
    }

}

$bot = new twitterbot;
$bot->connect('', '', '', '');

$bot->addblacklist(array("1390693447", "558800766", "2198265000"));

$bot->checkignore(array("ignore", "stop"), "You have been added to the ignore list. Any more problems? Contact https://twitter.com/jdf221");

$bot->action("run", $bot->search("#php OR #php5 OR #phpgd OR @phpstorm OR #phpdev"));

?>

Update use composer install of twitterOaUth


<?php

/**
 * This file is part of Bootstrap CMS by Graham Campbell.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 */

use GrahamCampbell\BootstrapCMS\Facades\PageRepository;

/*
|--------------------------------------------------------------------------
| Application Event Listeners
|--------------------------------------------------------------------------
|
| Here is where you can register all of the listeners for an application.
|
*/

if (Config::get('graham-campbell/core::commands')) {
    $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CommandSubscriber');
    Event::subscribe($subscriber);
}

$subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CoreSubscriber');
Event::subscribe($subscriber);

$subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\NavigationSubscriber');
Event::subscribe($subscriber);

$observer = App::make('GrahamCampbell\BootstrapCMS\Observers\PageObserver');
PageRepository::observe($observer);

<?php

/**
 * This file is part of Bootstrap CMS by Graham Campbell.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 */

use GrahamCampbell\BootstrapCMS\Facades\PageRepository;

/*
|--------------------------------------------------------------------------
| Application Event Listeners
|--------------------------------------------------------------------------
|
| Here is where you can register all of the listeners for an application.
|
*/

if (Config::get('graham-campbell/core::commands')) {
    $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CommandSubscriber');
    Event::subscribe($subscriber);
}

// $subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\CoreSubscriber');
// Event::subscribe($subscriber);

$subscriber = App::make('GrahamCampbell\BootstrapCMS\Subscribers\NavigationSubscriber');
Event::subscribe($subscriber);

$observer = App::make('GrahamCampbell\BootstrapCMS\Observers\PageObserver');
PageRepository::observe($observer);

Comment out broken subscriber for now

Comment out broken subscriber for now


<?php

namespace Symfony\Component\Config\Tests\Fixtures\Configuration;

use Symfony\Component\Config\Definition\Builder\NodeDefinition;

class CustomNodeDefinition extends NodeDefinition
{
    protected function createNode()
    {
        return new CustomNode();
    }
}

<?php

namespace Symfony\Component\Config\Tests\Fixtures\Configuration;

use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;

class CustomNodeDefinition extends NodeDefinition
{
    protected function createNode(): NodeInterface
    {
        return new CustomNode();
    }
}

Add missing return types to tests/internal/final methods


<?php

namespace sablonier\carousel;

use Bolt\Extension\SimpleExtension;

class CarouselExtension extends SimpleExtension
{

    /**
     * {@inheritdoc}
     */
    protected function registerTwigFunctions()
    {
        return [
            'carousel'    => ['carouselFunction']
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function registerTwigPaths()
    {
        return [
            'templates'
        ];
    }

    /**
     * Render and return the twig file templates/_carousel.twig
     *
     * @return carousel
     */
    public function carouselFunction($options)
    {

        $config = $this->getConfig();

        $context = [
            'options' => $options,
            'type' => $config['render']['type']
        ];

        switch ($config['render']['framework']) {
            case 'bootstrap4':
                $carousel = $this->renderTemplate('_carousel_bootstrap4.twig', $context);
                break;
            /*case 'foundation6':
                $carousel = $this->renderTemplate('_carousel_foundation6.twig', $context);
                break;
            case 'purecss':
                $carousel = $this->renderTemplate('_carousel_purecss.twig', $context);
                break;*/
        }

        echo $carousel;

    }

}

<?php

namespace sablonier\carousel;

use Bolt\Extension\SimpleExtension;

class CarouselExtension extends SimpleExtension
{

    /**
     * {@inheritdoc}
     */
    protected function registerTwigFunctions()
    {
        return [
            'carousel'    => ['carouselFunction']
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function registerTwigPaths()
    {
        return [
            'templates'
        ];
    }

    /**
     * Render and return the twig file templates/_carousel.twig
     *
     * @return carousel
     */
    public function carouselFunction($options)
    {

        $config = $this->getConfig();

        $context = [
            'options' => $options,
        ];

        switch ($config['render']['framework']) {
            case 'bootstrap4':
                $carousel = $this->renderTemplate('_carousel_bootstrap4.twig', $context);
                break;
            /*case 'foundation6':
                $carousel = $this->renderTemplate('_carousel_foundation6.twig', $context);
                break;
            case 'purecss':
                $carousel = $this->renderTemplate('_carousel_purecss.twig', $context);
                break;*/
        }

        echo $carousel;

    }

}

Stop mixing extension configuration and context options


<?php

namespace Jb\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('JbTestBundle:Default:index.html.twig', array('name' => $name));
    }
}

<?php

namespace Jb\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Jb\TestBundle\Domain\Command\Test1Command;

class DefaultController extends Controller
{
    public function indexAction($name)
    {

    	$this->get('broadway.command_handling.command_bus')->dispatch(new Test1Command($name));

        return $this->render('JbTestBundle:Default:index.html.twig', array('name' => $name));
    }
}

Make commande in default route

Make commande in default route


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => 'us-east-1',
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => eien\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

    'telegram-bot-api' => [
        'token' => env('TELEGRAM_BOT_TOKEN'),
    ],
];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => 'us-east-1',
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => eien\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

    'telegram-bot-api' => [
        'token' => env('TELEGRAM_BOT_TOKEN'),
        'username' => env('TELEGRAM_BOT_USERNAME'),
    ],
];

Allow telegram bot name to be configured


<?php

namespace BinSoul\Net\Mqtt;

/**
 * Represents the connection of a MQTT client.
 */
interface Connection
{
    /**
     * @return int
     */
    public function getProtocol();

    /**
     * @return int
     */
    public function getClientID();

    /**
     * @return bool
     */
    public function isCleanSession();

    /**
     * @return string
     */
    public function getUsername();

    /**
     * @return string
     */
    public function getPassword();

    /**
     * @return Message|null
     */
    public function getWill();

    /**
     * @return int
     */
    public function getKeepAlive();

    /**
     * Returns a new connection with the given protocol.
     *
     * @param int $protocol
     *
     * @return self
     */
    public function withProtocol($protocol);

    /**
     * Returns a new connection with the given client id.
     *
     * @param string $clientID
     *
     * @return self
     */
    public function withClientID($clientID);

    /**
     * Returns a new connection with the given credentials.
     *
     * @param string $username
     * @param string $password
     *
     * @return self
     */
    public function withCredentials($username, $password);

    /**
     * Returns a new connection with the given will.
     *
     * @param Message $will
     *
     * @return self
     */
    public function withWill(Message $will);

    /**
     * Returns a new connection with the given keep alive timeout.
     *
     * @param int $timeout
     *
     * @return self
     */
    public function withKeepAlive($timeout);
}

<?php

namespace BinSoul\Net\Mqtt;

/**
 * Represents the connection of a MQTT client.
 */
interface Connection
{
    /**
     * @return int
     */
    public function getProtocol();

    /**
     * @return string
     */
    public function getClientID();

    /**
     * @return bool
     */
    public function isCleanSession();

    /**
     * @return string
     */
    public function getUsername();

    /**
     * @return string
     */
    public function getPassword();

    /**
     * @return Message|null
     */
    public function getWill();

    /**
     * @return int
     */
    public function getKeepAlive();

    /**
     * Returns a new connection with the given protocol.
     *
     * @param int $protocol
     *
     * @return self
     */
    public function withProtocol($protocol);

    /**
     * Returns a new connection with the given client id.
     *
     * @param string $clientID
     *
     * @return self
     */
    public function withClientID($clientID);

    /**
     * Returns a new connection with the given credentials.
     *
     * @param string $username
     * @param string $password
     *
     * @return self
     */
    public function withCredentials($username, $password);

    /**
     * Returns a new connection with the given will.
     *
     * @param Message $will
     *
     * @return self
     */
    public function withWill(Message $will);

    /**
     * Returns a new connection with the given keep alive timeout.
     *
     * @param int $timeout
     *
     * @return self
     */
    public function withKeepAlive($timeout);
}

Fix type hint of connection interface

Fix type hint of connection interface


<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$app = array();

$app['config'] = array(
    'db' => array(
        'dsn'      => 'mysql:dbname=foler;host=localhost',
        'user'      => 'root',
        'password'  => 'CFGHNBV'
    )
);
$app['locale'] = 'en';

include 'ChromePhp.php';

<?php

$app = array();

$app['config'] = array(
    'db' => array(
        'dsn'      => 'mysql:dbname=foler;host=localhost',
        'user'      => 'root',
        'password'  => ''
    ),
    'debug' => false
);

if($app['config']['debug']):
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
endif;

$app['locale'] = 'en';

/**
 * Helps us split codes to associative array
 *
 * @param type $string
 * @param type $value
 * @param array $arr
 */
function joinStringToArr($string, $value, &$arr = array()) {

        $keys = explode('.', $string);

        $ref = &$arr;

        while ($key = array_shift($keys)) {
            $ref = &$ref[$key];
        }

        $ref = $value;

    }

Add debug to $app config

Add debug to $app config


<fieldset>
    <legend><?= t('Registration') ?></legend>
    <?= $this->form->label(t('Email domain restriction for sign up'), 'registration_email_domain') ?>
    <?= $this->form->text('registration_email_domain', $values, $errors, array('placeholder="domain1.tld, domain2.tld, domain3.tld"')) ?>

<?= t('Only people with this email address will be allowed to sign up.') ?>

</fieldset>

Add fieldset to config form

Add fieldset to config form


<?php defined('C5_EXECUTE') or die('Access denied.'); ?>

    <?=$form->label('apikey', t('Api Key'))?>

        <?=$form->text('apikey',$apikey)?>

    <?=$form->label('apisecret', t('Api Secret'))?>

        <?=$form->text('apisecret', $apisecret)?>

<?php defined('C5_EXECUTE') or die('Access denied.'); ?>

    <?=$form->label('apikey', t('Api Key'))?>

        <?=$form->text('apikey', $apikey)?>

    <?=$form->label('apisecret', t('Api Secret'))?>

        <?=$form->text('apisecret', $apisecret)?>

<?php echo t('Click here to obtain your access keys.', 'https://developers.facebook.com/apps/'); ?>

Add link to facebook apps page

Add link to facebook apps page

Former-commit-id: d8534d74ff9aad12672b552410eb6bb7864e87aa


<?php

namespace Application\MainBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GoCommand extends ContainerAwareCommand {

    protected function configure() {
        $this
                ->setName('go:show')
                ->setDescription('Symfony 2 command template.')
                ->addOption(
                        'yell', 'y', InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters'
                )
                ->addOption(
                        'msg', 'm', InputOption::VALUE_OPTIONAL, 'Custom message'
                )
        ;
    }

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

        $messages = __METHOD__;
        $output->writeln($messages);
    }

}

<?php

namespace Application\MainBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\LockHandler;

class GoCommand extends ContainerAwareCommand
{

    protected function configure()
    {
        $this
                ->setName('go')
                ->setDescription('Symfony 2 command template.')
                ->addOption(
                        'yell', 'y', InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters'
                )
                ->addOption(
                        'msg', 'm', InputOption::VALUE_OPTIONAL, 'Custom message'
                )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Create the lock:
        $lock = new LockHandler('go');
        if (!$lock->lock()) {
            return 0xFF;
        }

        $messages = __METHOD__;
        $output->writeln($messages);

        sleep(10);

        // Release the lock:
        $lock->release();
    }

}

Modify sample command - add process lock


<?php

namespace Hodor\Database\Phpmig;

use Phpmig\Adapter\AdapterInterface;
use Phpmig\Migration\Migration;

class PgsqlPhpmigAdapter implements AdapterInterface
{
    /**
     * connection returned by pg_connect()
     * @var resource
     */
    private $connection;

    /**
     * @param resource $connection - connection returned by pg_connect()
     */
    public function __construct($connection)
    {
        $this->connection = $connection;
    }

    public function fetchAll()
    {
    }

    public function up(Migration $migration)
    {
    }

    public function down(Migration $migration)
    {
    }

    public function hasSchema()
    {
        $sql = <<<SQL
SELECT 1
FROM pg_tables
WHERE schemaname = 'migrations'
    AND tablename = 'migrations'
SQL;

        $result = pg_query($this->connection, $sql);
        if ($row = pg_fetch_row($result)) {
            return (bool) $row[0];
        }

        return false;
    }

    public function createSchema()
    {
    }
}

<?php

namespace Hodor\Database\Phpmig;

use Phpmig\Adapter\AdapterInterface;
use Phpmig\Migration\Migration;

class PgsqlPhpmigAdapter implements AdapterInterface
{
    /**
     * connection returned by pg_connect()
     * @var resource
     */
    private $connection;

    /**
     * @param resource $connection - connection returned by pg_connect()
     */
    public function __construct($connection)
    {
        $this->connection = $connection;
    }

    public function fetchAll()
    {
    }

    public function up(Migration $migration)
    {
    }

    public function down(Migration $migration)
    {
    }

    public function hasSchema()
    {
        $sql = <<<SQL
SELECT 1
FROM pg_tables
WHERE schemaname = 'migrations'
    AND tablename = 'migrations'
SQL;

        $result = pg_query($this->connection, $sql);
        if ($row = pg_fetch_row($result)) {
            return (bool) $row[0];
        }

        return false;
    }

    public function createSchema()
    {
        $sql = <<<SQL
CREATE SCHEMA migrations;

CREATE TABLE migrations.migrations
(
    version VARCHAR PRIMARY KEY,
    migrated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
SQL;

        pg_query($this->connection, $sql);

        return $this;
    }
}

Add migrations.migrations table for tracking DB updates


<?php

namespace Styde\Html\Tests;

use Styde\Html\FormModel\Field;
use Styde\Html\FormModel\FieldCollection;

class FieldCollectionTest extends TestCase
{
    /** @test */
    function it_adds_a_field()
    {
        $fields = new FieldCollection(field());

        $fields->add('first_name', 'text');

        $this->assertInstanceOf(Field::class, $fields->first_name);
    }

    /** @test */
    function it_renders_fields()
    {
        $fields = new FieldCollection(field());

        $fields->add('name')->label('Full name');
        $fields->add('role', 'select')->options(['admin' => 'Admin' , 'user' => 'User']);

        $this->assertTemplateMatches('field-collection/fields', $fields->render());
    }
}

<?php

namespace Styde\Html\Tests;

use Styde\Html\FormModel\Field;
use Styde\Html\FormModel\FieldCollection;

class FieldCollectionTest extends TestCase
{
    /** @test */
    function it_adds_a_field()
    {
        $fields = new FieldCollection(field());

        $fields->add('first_name', 'text');

        $this->assertInstanceOf(Field::class, $fields->first_name);
    }

    /** @test */
    function it_renders_fields()
    {
        $fields = new FieldCollection(field());

        $fields->add('name')->label('Full name');
        $fields->add('role', 'select')->options(['admin' => 'Admin' , 'user' => 'User']);

        $this->assertTemplateMatches('field-collection/fields', $fields->render());
    }

    /** @test */
    function it_render_field_password_with_required_rule()
    {
        $fields = new FieldCollection(field());

        $fields->password('password')->required();

        $this->assertTemplateMatches('field-collection/fields', $fields->render());
    }
}

Add test field password with required rule


<?php

namespace DrawMyAttention\ExpAuth;

use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use App\User;

class ExpressionEngineUserProvider extends EloquentUserProvider{

    public function __construct(HasherContract $hasher, $model)
    {
        parent::__construct($hasher, $model);
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain                  = $credentials['password'];
        $options = array();
        if ($user instanceof App\User) {
            $options['salt']        = $user->salt;
            $options['byte_size']   = strlen($user->getAuthPassword());
        }
        return $this->hasher->check($plain, $user->getAuthPassword(), $options);
    }

}

<?php

namespace DrawMyAttention\ExpAuth;

use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use App\User;

class ExpressionEngineUserProvider extends EloquentUserProvider{

    public function __construct(HasherContract $hasher, $model)
    {
        parent::__construct($hasher, $model);
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain                  = $credentials['password'];
        $options = array();
        if ($user instanceof User) {
            $options['salt']        = $user->salt;
            $options['byte_size']   = strlen($user->getAuthPassword());
        }
        return $this->hasher->check($plain, $user->getAuthPassword(), $options);
    }

}

Fix namespacing of User class

Fix namespacing of User class


<?php

/**
 * @author AIZAWA Hina <hina@fetus.jp>
 * @copyright 2015-2019 by AIZAWA Hina <hina@fetus.jp>
 * @license https://github.com/fetus-hina/yii2-extra-validator/blob/master/LICENSE MIT
 * @since 1.0.1
 */

namespace jp3cki\yii2\validators;

use yii\validators\FilterValidator;

/**
 * The filter validator which converts IDN to Punycoded domain name
 */
class IdnToPunycodeFilterValidator extends FilterValidator
{
    /** @inheritdoc */
    public function init()
    {
        $this->filter = function ($value) {
            if (strpos($value, '/') === false) {
                return strtolower(idn_to_ascii($value));
            }
            if (strpos($value, '//') !== false) {
                return preg_replace_callback(
                    '!(?<=//)([^/:]+)!',
                    function ($match) {
                        return strtolower(idn_to_ascii($match[1]));
                    },
                    $value,
                    1
                );
            }
            return preg_replace_callback(
                '!^([^/:]+)!',
                function ($match) {
                    return strtolower(idn_to_ascii($match[1]));
                },
                $value,
                1
            );
        };
        parent::init();
    }
}

<?php

/**
 * @author AIZAWA Hina <hina@fetus.jp>
 * @copyright 2015-2019 by AIZAWA Hina <hina@fetus.jp>
 * @license https://github.com/fetus-hina/yii2-extra-validator/blob/master/LICENSE MIT
 * @since 1.0.1
 */

namespace jp3cki\yii2\validators;

use yii\validators\FilterValidator;

use function idn_to_ascii;

use const INTL_IDNA_VARIANT_UTS46;

/**
 * The filter validator which converts IDN to Punycoded domain name
 */
class IdnToPunycodeFilterValidator extends FilterValidator
{
    /** @inheritdoc */
    public function init()
    {
        $this->filter = function (string $value): string {
            if (strpos($value, '/') === false) {
                return strtolower(static::idnToAscii($value));
            }

            if (strpos($value, '//') !== false) {
                return preg_replace_callback(
                    '!(?<=//)([^/:]+)!',
                    function (array $match): string {
                        return strtolower(static::idnToAscii($match[1]));
                    },
                    $value,
                    1
                );
            }

            return preg_replace_callback(
                '!^([^/:]+)!',
                function (array $match): string {
                    return strtolower(static::idnToAscii($match[1]));
                },
                $value,
                1
            );
        };
        parent::init();
    }

    protected static function idnToAscii(string $value): string
    {
        return idn_to_ascii($value, 0, INTL_IDNA_VARIANT_UTS46);
    }
}

Use INTL_IDNA_VARIANT_UTS46 instead of INTL_IDNA_VARIANT_2003


<?php
namespace App\Http\Livewire;

use Livewire\Component;

class LoginForm extends Component
{
    public $username = '';
    public $password = '';
    public $can_submit = false;

    /**
     * Set the validation rules for login
     *
     * @author  A. Ginaotto <snipe@snipe.net>
     * @version v6.0
     * @return Array
     */
    public function rules()
    {
        return [
            'username' => 'required|string|max:255',
            'password' => 'required',
        ];
    }

    /**
     * Perform the validation
     *
     * @author  A. Ginaotto <snipe@snipe.net>
     * @version v6.0
     */
    public function updated($fields)
    {
        $this->validateOnly($fields);

        if (!is_null($fields) && !empty($fields)) {
            $this->can_submit = true;
        } else {
            $this->can_submit = false;
        }

    }

    /**
     * Actually do the login thing
     *
     * @todo fix missing LDAP stuff maybe?
     * @author  A. Ginaotto <snipe@snipe.net>
     * @version v6.0
     */
    public function submitForm()
    {

        $validatedData = $this->validate();

        if (\Auth::attempt(array('username' => $this->username, 'password' => $this->password))){
            redirect()->route('dashboard');
        } else {
            session()->flash('error', 'email and password are wrong.');
    }

    }

}

<?php
namespace App\Http\Livewire;

use Livewire\Component;

class LoginForm extends Component
{
    public $username = '';
    public $password = '';
    public $can_submit = false;

    /**
     * Set the validation rules for login
     *
     * @author  A. Ginaotto <snipe@snipe.net>
     * @version v6.0
     * @return Array
     */
    public function rules()
    {
        return [
            'username' => 'required|string|max:255',
            'password' => 'required',
        ];
    }

    /**
     * Perform the validation
     *
     * @author  A. Ginaotto <snipe@snipe.net>
     * @version v6.0
     */
    public function updated($fields)
    {
        $this->validateOnly($fields);

        if (!is_null($fields) && !empty($fields)) {
            $this->can_submit = true;
        } else {
            $this->can_submit = false;
        }

    }

    /**
     * Actually do the login thing
     *
     * @todo fix missing LDAP stuff maybe?
     * @author  A. Ginaotto <snipe@snipe.net>
     * @version v6.0
     */
    public function submitForm()
    {

        $validatedData = $this->validate();

        if (\Auth::attempt(
            [
                'username' => $this->username,
                'password' => $this->password
            ]
            ))
            {
            redirect()->route('dashboard');
        } else {
            session()->flash('error', trans('auth/message.account_not_found'));
        }

    }

}

Use correct auth failure message

Use correct auth failure message

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


<?php

/*
 * This file is part of HtmlCompress.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\HtmlCompress\Tests\SpecialFormats;

use WyriHaximus\HtmlCompress\Compressor;

class LdJsonTest extends \PHPUnit_Framework_TestCase
{
    public function javascriptCompressorProvider()
    {
        return [
            [
                new Compressor\JSMinCompressor(),
            ],
        ];
    }

    /**
     * @dataProvider javascriptCompressorProvider
     */
    public function testLdJson(Compressor\CompressorInterface $compressor)
    {
        $input = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'input' . DIRECTORY_SEPARATOR . 'ld.json.input');
        $inputJson = $this->getJson($input);
        $compressedInput = $compressor->compress($input);
        $compressedJson = $this->getJson($compressedInput);

        self::assertSame($inputJson, $compressedJson);
    }

    private function getJson($string)
    {
        $start = strpos($string, '{');
        $end = strrpos($string, '}') + 1;
        $string = substr($string, $start, $end - $start);

        return json_decode($string, true);
    }
}

<?php

/*
 * This file is part of HtmlCompress.
 *
 ** (c) 2014 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace WyriHaximus\HtmlCompress\Tests\SpecialFormats;

use WyriHaximus\HtmlCompress\Compressor;

class LdJsonTest extends \PHPUnit_Framework_TestCase
{
    public function javascriptCompressorProvider()
    {
        return [
            [
                new Compressor\JSMinCompressor(),
            ],
            [
                new Compressor\JavaScriptPackerCompressor(),
            ],
            /*[ // This compressor results in invalid JSON
                new Compressor\JSqueezeCompressor(),
            ],*/
            [
                new Compressor\ReturnCompressor(),
            ],
        ];
    }

    /**
     * @dataProvider javascriptCompressorProvider
     */
    public function testLdJson(Compressor\CompressorInterface $compressor)
    {
        $input = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'input' . DIRECTORY_SEPARATOR . 'ld.json.input');
        $inputJson = $this->getJson($input);
        $compressedInput = $compressor->compress($input);
        $compressedJson = $this->getJson($compressedInput);

        self::assertSame($inputJson, $compressedJson, $compressedInput);
    }

    private function getJson($string)
    {
        $start = strpos($string, '{');
        $end = strrpos($string, '}') + 1;
        $string = substr($string, $start, $end - $start);

        return json_decode($string, true);
    }
}

Test against all javascript compressors, and the return compressor for reference


<?PHP  //$Id$
// This file defines the current version of the
// Moodle code that is being used.  This can be
// compared against the values stored in the
// database to determine whether upgrades should
// be performed (see lib/db/*.php)

$version = 2003032602;   // The current version is a date (YYYYMMDDXX)

$release = "1.0.9 development";  // User-friendly version number

<?PHP  //$Id$
// This file defines the current version of the
// Moodle code that is being used.  This can be
// compared against the values stored in the
// database to determine whether upgrades should
// be performed (see lib/db/*.php)

$version = 2003041200;   // The current version is a date (YYYYMMDDXX)

$release = "1.0.9 development";  // User-friendly version number

Update to stop it falling too far behind


<?php namespace App\Services;

class Purchase
{
    /**
     *
     * Purchase book function
     *
     * @param $book \App\Book
     * @param $bookPurchaseQty integer
     * @return array
     */
    public function purchaseBook($book , $bookPurchaseQty)
    {
        $bookPrice = $book->price;
        $bookAvailableQty = $book->quantity;
        $response = [];

        if($bookPurchaseQty > $bookAvailableQty) {
            $response = ['message' => 'Book quantity not available' , 'data'=> ''];
        }

        return $response;
    }
}

<?php namespace App\Services;

class Purchase
{
    /**
     *
     * Purchase book function
     *
     * @param $book \App\Book
     * @param $bookPurchaseQty integer
     * @return array
     */
    public function purchaseBook($book , $bookPurchaseQty)
    {
        $bookPrice = $book->price;
        $bookAvailableQty = $book->quantity;
        $purchasePrice = null;

        if($bookPurchaseQty > $bookAvailableQty) {
            $purchasePrice = $bookPurchaseQty * $bookPrice;
        }

        return $purchasePrice;
    }
}

Add purchase functionality in back-end.

Add purchase functionality in back-end.


<?php

namespace spec\Swarrot\Processor\Stack;

use Swarrot\Processor\InitializableInterface;
use Swarrot\Processor\TerminableInterface;
use Swarrot\Processor\ProcessorInterface;
use Swarrot\ParameterBag;
use Swarrot\AMQP\Message;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class StackedProcessorSpec extends ObjectBehavior
{
    function it_is_initializable(InitializableProcessor $p1, TerminableProcessor $p2)
    {
        $this->beConstructedWith(array($p1, $p2));
        $this->shouldHaveType('Swarrot\Processor\Stack\StackedProcessor');
    }
}

class InitializableProcessor implements InitializableInterface {
    public function initialize(ParameterBag $bag) {}
}

class TerminableProcessor implements TerminableInterface {
    public function terminate(ParameterBag $bag) {}
}

<?php

namespace spec\Swarrot\Processor\Stack;

use Swarrot\Processor\InitializableInterface;
use Swarrot\Processor\TerminableInterface;
use Swarrot\Processor\ProcessorInterface;
use Swarrot\ParameterBag;
use Swarrot\AMQP\Message;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class StackedProcessorSpec extends ObjectBehavior
{
    function it_is_initializable(ProcessorInterface $p1, InitializableProcessor $p2, TerminableProcessor $p3)
    {
        $this->beConstructedWith($p1, array($p2, $p3));
        $this->shouldHaveType('Swarrot\Processor\Stack\StackedProcessor');
    }
}

class InitializableProcessor implements InitializableInterface {
    public function initialize(ParameterBag $bag) {}
}

class TerminableProcessor implements TerminableInterface {
    public function terminate(ParameterBag $bag) {}
}

Correct wrong constructor in test

Correct wrong constructor in test


<?php

namespace Oro\Bundle\EntityConfigBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class AttributeFamilyGroups extends Constraint
{
    /**
     * @var string
     */
    public $emptyGroupsMessage = 'oro.entity_config.validator.attribute_family.empty_groups';

    /**
     * @var string
     */
    public $manyDefaultGroupsMessage = 'oro.entity_config.validator.attribute_family.many_default_groups';

    /**
     * @var string
     */
    public $defaultGroupIsNotExistMessage = 'oro.entity_config.validator.attribute_family.default_group_is_not_exist';

    /**
     * @var string
     */
    public $sameLabelsMessage = 'oro.entity_extend.validator.attribute_family.same_labels';

    /**
     * {@inheritdoc}
     */
    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

    /**
     * {@inheritdoc}
     */
    public function validatedBy()
    {
        return AttributeFamilyGroupsValidator::ALIAS;
    }
}

<?php

namespace Oro\Bundle\EntityConfigBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class AttributeFamilyGroups extends Constraint
{
    /**
     * @var string
     */
    public $emptyGroupsMessage = 'oro.entity_config.validator.attribute_family.empty_groups';

    /**
     * @var string
     */
    public $manyDefaultGroupsMessage = 'oro.entity_config.validator.attribute_family.many_default_groups';

    /**
     * @var string
     */
    public $defaultGroupIsNotExistMessage = 'oro.entity_config.validator.attribute_family.default_group_is_not_exist';

    /**
     * @var string
     */
    public $sameLabelsMessage = 'oro.entity_config.validator.attribute_family.same_labels';

    /**
     * {@inheritdoc}
     */
    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

    /**
     * {@inheritdoc}
     */
    public function validatedBy()
    {
        return AttributeFamilyGroupsValidator::ALIAS;
    }
}

BB-6143: Add code property for attribute group
- fix translation key


<?php

$config = array(

	'store' 	=> array(
		'consent:Database',
		'dsn' => 'pgsql:host=sql.uninett.no;dbname=andreas_consent',
		'username' => 'simplesaml',
		'password' => 'xxxx',
	),

	'auth' => 'example-static',
	'userid', 'eduPersonPrincipalName',

);

<?php

$config = array(

	'store' 	=> array(
		'consent:Database',
		'dsn' => 'pgsql:host=sql.uninett.no;dbname=andreas_consent',
		'username' => 'simplesaml',
		'password' => 'xxxx',
	),

	'auth' => 'example-static',
	'userid' => 'eduPersonPrincipalName',

);

Fix default configuration for consentAdmin & consentSimpleAdmin.

Thanks to François Kooman for providing this patch!

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


<?php

// To run this test, You need to install PHPUnit and Selenium RC Server
// Selenium RC Server is available the following website.
// http://openqa.org/selenium-rc/
//error_reporting(E_ALL|E_STRICT);
set_include_path(get_include_path() . PATH_SEPARATOR . './PEAR/');
require_once 'Testing/Selenium.php';
require_once 'PHPUnit/Framework/TestCase.php';

class GoogleTest extends PHPUnit_Framework_TestCase
{
    private $selenium;

    public function __construct($name)
    {
        $this->browserUrl = "http://www.google.com";
        parent::__construct($name);
    }
// {{{ setUp and tearDown
    public function setUp()
    {
        try {
            $this->selenium = new Testing_Selenium("*firefox", $this->browserUrl);
            $this->selenium->start();
        } catch (Testing_Selenium_Exception $e) {
            $this->selenium->stop();
            echo $e;
        }
    }

    public function tearDown()
    {
        $this->selenium->stop();
    }

    public function testGoogle()
    {
        $this->selenium->open("/");
        $this->selenium->type("q", "hello world");
        $this->selenium->click("btnG");
        $this->selenium->waitForPageToLoad(10000);
        $this->assertRegExp("/Google Search/", $this->selenium->getTitle());
    }

}
?>

<?php

set_include_path(get_include_path() . PATH_SEPARATOR . './PEAR/');
require_once 'Testing/Selenium.php';
require_once 'PHPUnit/Framework/TestCase.php';

class GoogleTest extends PHPUnit_Framework_TestCase
{
    private $selenium;

    public function setUp()
    {
        $this->selenium = new Testing_Selenium("*firefox", "http://www.google.com");
        $this->selenium->start();
    }

    public function tearDown()
    {
        $this->selenium->stop();
    }

    public function testGoogle()
    {
        $this->selenium->open("/");
        $this->selenium->type("q", "hello world");
        $this->selenium->click("btnG");
        $this->selenium->waitForPageToLoad(10000);
        $this->assertRegExp("/Google Search/", $this->selenium->getTitle());
    }

}
?>

Clean up this test a bit; it's a proper example

r3683


Disable tab stop on password show/hide links


<?php

use SilverStripe\Omnipay\Service\ServiceResponse;

/**
 * Customisations to {@link Payment} specifically for the shop module.
 *
 * @package shop
 */
class ShopPayment extends DataExtension
{
    private static $has_one = array(
        'Order' => 'Order',
    );

    public function onAwaitingAuthorized(ServiceResponse $response)
    {
        $this->placeOrder();
    }

    public function onAwaitingCaptured(ServiceResponse $response)
    {
        $this->placeOrder();
    }

    public function onAuthorized(ServiceResponse $response)
    {
        $this->placeOrder();
    }

    public function onCaptured(ServiceResponse $response)
    {
        $order = $this->owner->Order();
        if ($order->exists()) {
            OrderProcessor::create($order)->completePayment();
        }
    }

    protected function placeOrder()
    {
        $order = $this->owner->Order();
        if ($order->exists()) {
            OrderProcessor::create($order)->placeOrder();
        }
    }
}

<?php

use SilverStripe\Omnipay\Service\ServiceResponse;

/**
 * Customisations to {@link Payment} specifically for the shop module.
 *
 * @package shop
 */
class ShopPayment extends DataExtension
{
    private static $has_one = array(
        'Order' => 'Order',
    );

    public function onAwaitingAuthorized(ServiceResponse $response)
    {
        $this->placeOrder();
    }

    public function onAwaitingCaptured(ServiceResponse $response)
    {
        $this->placeOrder();
    }

    public function onAuthorized(ServiceResponse $response)
    {
        $this->placeOrder();
    }

    public function onCaptured(ServiceResponse $response)
    {
        // ensure order is being reloaded from DB, to prevent dealing with stale data!
        /** @var Order $order */
        $order = Order::get()->byID($this->owner->OrderID);
        if ($order && $order->exists()) {
            OrderProcessor::create($order)->completePayment();
        }
    }

    protected function placeOrder()
    {
        // ensure order is being reloaded from DB, to prevent dealing with stale data!
        /** @var Order $order */
        $order = Order::get()->byID($this->owner->OrderID);
        if ($order && $order->exists()) {
            OrderProcessor::create($order)->placeOrder();
        }
    }
}

Fix shop-payment by enforcing order reload.