<?php

require 'letterScore.php';

$input = hex2bin("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
$inputLength = strlen($input);
$scores = [];

for ($kv=0; $kv < 256; $kv++) {
  $charScore = 0;
  $plainText = "";

  for ($i=0; $i < strlen($input); $i++) {
    $plainText .= $input{$i} ^ chr($kv);
  }

  $charScore = englishLetterWeight($plainText, 0.5);

  $scores[chr($kv)] = $charScore;

}

arsort($scores);

$keyCount = 0;
foreach ($scores as $key => $value) {
  if ($keyCount < 3) {
    $decrypt = $input ^ str_repeat($key, $inputLength);
    echo "'$key' (" . ord($key) . ") : " . $decrypt . "\n";
  } else {
    break;
  }

  $keyCount++;

}

?>

<?php

require 'letterScore.php';

$input = hex2bin("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736");
$inputLength = strlen($input);
$scores = [];

for ($kv=0; $kv < 256; $kv++) {
  $charScore = 0;
  $plainText = "";

  for ($i=0; $i < $inputLength; $i++) {
    $plainText .= $input{$i} ^ chr($kv);
  }

  $charScore = englishLetterWeight($plainText, 0.5);

  $scores[chr($kv)] = $charScore;

}

arsort($scores);

$keyCount = 0;
foreach ($scores as $key => $value) {
  if ($keyCount < 3) {
    $decrypt = '';

    for ($i=0; $i < $inputLength; $i++) {
      $decrypt .= $input{$i} ^ $key;
    }

    echo "'$key' (" . ord($key) . ") : " . $decrypt . "\n";
  } else {
    break;
  }

  $keyCount++;

}

?>

Change final decrypt to speed up output

Change final decrypt to speed up output

Testing showed that a for loop was faster at decryting than using
str_repeat, so both scoring, and final decrypt now use a loop.


<?php

namespace TypiCMS\Modules\Core\Http\Middleware;

use Closure;

class SetTranslatableFallbackLocaleToNull
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        config(['app.fallback_locale' => null]);

        return $next($request);
    }
}

<?php

namespace TypiCMS\Modules\Core\Http\Middleware;

use Closure;

class SetTranslatableFallbackLocaleToNull
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        config(['app.fallback_locale' => null]);
        config(['translatable.fallback_locale' => null]);

        return $next($request);
    }
}

Disable translatable fallback locale in admin


<?php

namespace Oro\Bundle\EmailBundle\EventListener;

use Symfony\Component\Security\Core\User\UserInterface;

use Oro\Bundle\SearchBundle\Event\PrepareEntityMapEvent;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\EmailRecipient;
use Oro\Bundle\OrganizationBundle\Entity\OrganizationAwareInterface;

class SearchListener
{
    const EMAIL_CLASS_NAME = 'Oro\Bundle\EmailBundle\Entity\Email';

    /**
     * @param PrepareEntityMapEvent $event
     */
    public function prepareEntityMapEvent(PrepareEntityMapEvent $event)
    {
        $data = $event->getData();
        $className = $event->getClassName();
        if ($className === self::EMAIL_CLASS_NAME) {
            /** @var $entity Email */
            $entity = $event->getEntity();
            $organizationsId = [];
            $recipients = $entity->getRecipients();
            /** @var  $recipient EmailRecipient */
            foreach ($recipients as $recipient) {
                $owner = $recipient->getEmailAddress()->getOwner();
                if ($owner instanceof UserInterface && $owner instanceof OrganizationAwareInterface) {
                    $organizationsId[] = $owner->getOrganization()->getId();
                }
            }
            if (!empty($organizationsId)) {
                $data['integer']['organization'] = array_unique($organizationsId);
            } else {
                $data['integer']['organization'] = 0;
            }
        }

        $event->setData($data);
    }
}

<?php

namespace Oro\Bundle\EmailBundle\EventListener;

use Symfony\Component\Security\Core\User\UserInterface;

use Oro\Bundle\SearchBundle\Event\PrepareEntityMapEvent;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\EmailRecipient;
use Oro\Bundle\OrganizationBundle\Entity\OrganizationAwareInterface;

class SearchListener
{
    const EMAIL_CLASS_NAME = 'Oro\Bundle\EmailBundle\Entity\Email';
    const EMPTY_ORGANIZATION_ID = 0;

    /**
     * @param PrepareEntityMapEvent $event
     */
    public function prepareEntityMapEvent(PrepareEntityMapEvent $event)
    {
        $data      = $event->getData();
        $className = $event->getClassName();
        if ($className === self::EMAIL_CLASS_NAME) {
            /** @var $entity Email */
            $entity          = $event->getEntity();
            $organizationsId = [];
            $recipients      = $entity->getRecipients();
            /** @var  $recipient EmailRecipient */
            foreach ($recipients as $recipient) {
                $owner = $recipient->getEmailAddress()->getOwner();
                if ($owner instanceof UserInterface && $owner instanceof OrganizationAwareInterface) {
                    $organizationsId[] = $owner->getOrganization()->getId();
                }
            }
            if (!isset ($data['integer'])) {
                $data['integer'] = [];
            }
            if (!empty($organizationsId)) {
                $data['integer']['organization'] = array_unique($organizationsId);
            } else {
                $data['integer']['organization'] = self::EMPTY_ORGANIZATION_ID;
            }
        }

        $event->setData($data);
    }
}

BAP-3724: Add email owners to search index
  - Fix cs


(9 sloc)  0.317 kb RawBlameHistory
<?php #YOLO
namespace yolo;
class_alias('Symfony\Component\HttpFoundation\Request', Request::class);
class_alias('Symfony\Component\HttpFoundation\Response', Response::class);
function yolo($controller) {
    $request = Request::createFromGlobals();
    $response = $controller($request);
    $response->send();
    unlink(__FILE__);
}

Make it actually live once, not never

Make it actually live once, not never


<?php
$message = ""; // initial message
echo($_POST['request_data']);
if( isset($_POST['request_data']) ){

	// Includes database connection
	include "db_connect.php";

	// Gets the data from post
	$name = $_POST['request_data'];

	// Makes query with post data
    $statement = $db->prepare('INSERT INTO requests(name) VALUES (:name);');
    $statement->bindValue(':name', $name, SQLITE3_TEXT); // Bind Value

    // Executes the query
    $result = $statement->execute();

    // Close Statement
    $statement->close();

	// Executes the query
	// If data inserted then set success message otherwise set error message
	// Here $db comes from "db_connection.php"
	if( $result ){
		$message = "Data is inserted successfully.";
	}else{
		$message = "Sorry, Data is not inserted.";
	}
}
?>

<?php
$message = ""; // initial message
echo($_POST['request_data']);
if( isset($_POST['request_data']) ){

	// Includes database connection
	include "db_connect.php";

	// Gets the data from post
	$name = $_POST['request_data'];

	// Makes query with post data
    $statement = $db->prepare('INSERT INTO requests(name, filled) VALUES (:name, :filled);');
    $statement->bindValue(':name', $name, SQLITE3_TEXT); // Bind Value
    $statement->bindValue(':filled', 0, SQLITE3_INTEGER); // Bind Value

    // Executes the query
    $result = $statement->execute();

    // Close Statement
    $statement->close();

	// Executes the query
	// If data inserted then set success message otherwise set error message
	// Here $db comes from "db_connection.php"
	if( $result ){
		$message = "Data is inserted successfully.";
	}else{
		$message = "Sorry, Data is not inserted.";
	}
}
?>

Insert Filled Value as Well, otherwise SQLite saves NULL


<?php declare(strict_types=1);

namespace Symplify\Tests\PHPUnit\Listener;

use Nette\Utils\FileSystem;
use Nette\Utils\Finder;
use Nette\Utils\Strings;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
use SplFileInfo;

final class ClearLogAndCacheTestListener implements TestListener
{
    use TestListenerDefaultImplementation;

    public function endTestSuite(TestSuite $testSuite): void
    {
        if ($testSuite->getName()) { // skip for tests, run only for whole Test Suite
            return;
        }

        foreach ($this->getTempDirectories() as $path => $info) {
            FileSystem::delete($path);
        }
    }

    /**
     * @return string[]
     */
    private function getTempDirectories(): array
    {
        $finder = Finder::findDirectories('cache', 'logs')
            ->from([
                __DIR__ . '/../../../packages',
                sys_get_temp_dir() . '/_statie_kernel',
                sys_get_temp_dir() . '/_easy_coding_standard'
            ]);

        $directories = iterator_to_array($finder->getIterator());

        $tempDirectories = array_filter($directories, function (SplFileInfo $file): bool {
            return ! Strings::contains($file->getPathname(), 'Cache');
        });

        return $tempDirectories;
    }
}

<?php declare(strict_types=1);

namespace Symplify\Tests\PHPUnit\Listener;

use Nette\Utils\FileSystem;
use Nette\Utils\Finder;
use Nette\Utils\Strings;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
use SplFileInfo;

final class ClearLogAndCacheTestListener implements TestListener
{
    use TestListenerDefaultImplementation;

    public function endTestSuite(TestSuite $testSuite): void
    {
        if ($testSuite->getName() !== 'all') { // skip for tests, run only for whole Test Suite
            return;
        }

        foreach ($this->getTempDirectories() as $path => $info) {
            FileSystem::delete($path);
        }
    }

    /**
     * @return string[]
     */
    private function getTempDirectories(): array
    {
        $finder = Finder::findDirectories('cache', 'logs')
            ->from([
                __DIR__ . '/../../../packages',
                sys_get_temp_dir() . '/_statie_kernel',
                sys_get_temp_dir() . '/_easy_coding_standard'
            ]);

        $directories = iterator_to_array($finder->getIterator());

        $tempDirectories = array_filter($directories, function (SplFileInfo $file): bool {
            return ! Strings::contains($file->getPathname(), 'Cache');
        });

        return $tempDirectories;
    }
}

Fix PHPUnit cleanup listener on suite name change


<?php

namespace AppBundle\Controller;

use AppBundle\Form\XoGridType;
use AppBundle\Game\GridFactory;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $grid = $this->getGridFactory()->createStandardGrid();

        $form = $this->createForm(new XoGridType(), $grid);

        $form->handleRequest($request);

        if (false !== $winner = $grid->getWinner()) {
            $request->getSession()->getFlashBag()->add('winner', 'The winner is ' . $winner);
        }

        return $this->render('default/index.html.twig', ['form' => $form->createView()]);
    }

    /**
     * @return GridFactory
     */
    private function getGridFactory()
    {
        $this->get('grid_factory');
    }
}

<?php

namespace AppBundle\Controller;

use AppBundle\Form\XoGridType;
use AppBundle\Game\GridFactory;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $grid = $this->getGridFactory()->createStandardGrid();

        $form = $this->createForm(new XoGridType(), $grid);

        $form->handleRequest($request);

        if (false !== $winner = $grid->getWinner()) {
            $request->getSession()->getFlashBag()->add('winner', 'The winner is ' . $winner);
        }

        return $this->render('default/index.html.twig', ['form' => $form->createView()]);
    }

    /**
     * @return GridFactory
     */
    private function getGridFactory()
    {
        return $this->get('grid_factory');
    }
}

Fix getting grid factory in controller

Fix getting grid factory in controller


<?php

$username = $_POST['username'];
$distance = $_POST['distance'];
$con = mysqli_connect("localhost","thedreamteam","El3ven","SSA") or die ("Error " . mysqli_error($con));

$query = mysqli_query($con,"UPDATE `Top Player` SET Distance=$distance WHERE PlayerName='$username'");
echo $query;

<?php

$username = $_GET['username'];
$distance = $_GET['distance'];
$con = mysqli_connect("localhost","thedreamteam","El3ven","SSA") or die ("Error " . mysqli_error($con));

$query = mysqli_query($con,"UPDATE `Top Player` SET Distance=$distance WHERE PlayerName='$username'");
echo $query;

Revert "Change GET to POST"

Revert "Change GET to POST"

This reverts commit 159f2b52c19d7335396224d5dadc35a4b9e13e3e.


<?php namespace Orchestra\Support\Ftp;

class RuntimeException extends \RuntimeException {

	/**
	 * Parameters.
	 *
	 * @var array
	 */
	protected $parameters = array();

	/**
	 * Construct a new exception.
	 *
	 * @param  string   $exception
	 * @param  array    $parameters
	 * @return void
	 */
	public function __construct($exception, array $parameters = array())
	{
		$this->parameters = $parameters;
		parent::__construct($exception);
	}
}

<?php namespace Orchestra\Support\Ftp;

class RuntimeException extends \RuntimeException {

	/**
	 * Parameters.
	 *
	 * @var array
	 */
	protected $parameters = array();

	/**
	 * Construct a new exception.
	 *
	 * @param  string   $exception
	 * @param  array    $parameters
	 * @return void
	 */
	public function __construct($exception, array $parameters = array())
	{
		$this->parameters = $parameters;
		parent::__construct($exception);
	}

	/**
	 * Get exceptions parameters.
	 *
	 * @return array
	 */
	public function getParameters()
	{
		return $this->parameters;
	}
}

Allow to get exceptions parameters.

Allow to get exceptions parameters.

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


<?php

/**
 * @copyright 2018 Vladimir Jimenez
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\MarkupEngine;

interface MarkupEngine
{
    const CONTAINER_TAG = 'stakx.markup_engine';

    /**
     * Get the custom tag and filter to register with our templating engine.
     *
     * For the Markdown engine, we'd be registering a tag called 'markdown' and a filter called 'markdown' to support
     * the following example.
     *
     * ```twig
     * {% markdown %}{% endmarkdown %}
     *
     * {{ 'my content' | markdown }}
     * ```
     *
     * @return null|string If null, then no tag or filter will be registered.
     */
    public function getTemplateTag();

    /**
     * List of extensions this engine will accept and parse.
     *
     * @return string[]
     */
    public function getExtensions();

    /**
     * Parse a given string using this engine.
     *
     * @param string $content
     *
     * @return string
     */
    public function parse($content);
}

<?php

/**
 * @copyright 2018 Vladimir Jimenez
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\MarkupEngine;

/**
 * This interface defines the markup engines stakx will know how to parse as ContentItems and as regular text within
 * Twig by registering custom tags and filters.
 *
 * @since 0.2.0
 */
interface MarkupEngine
{
    const CONTAINER_TAG = 'stakx.markup_engine';

    /**
     * Get the custom tag and filter to register with our templating engine.
     *
     * For the Markdown engine, we'd be registering a tag called 'markdown' and a filter called 'markdown' to support
     * the following example.
     *
     * ```twig
     * {% markdown %}my content{% endmarkdown %}
     *
     * {{ 'my content' | markdown }}
     * ```
     *
     * @since 0.2.0
     *
     * @return null|string If null, then no tag or filter will be registered.
     */
    public function getTemplateTag();

    /**
     * List of file extensions this engine will be charged with parsing.
     *
     * @since 0.2.0
     *
     * @return string[]
     */
    public function getExtensions();

    /**
     * Parse a given string using this engine.
     *
     * @param string $content
     *
     * @since 0.2.0
     *
     * @return string
     */
    public function parse($content);
}

Update some documentation for the interface

[ci skip]


<?php

declare(strict_types=1);

namespace Cortex\Fort\Console\Commands;

use Rinvex\Fort\Console\Commands\MigrateCommand as BaseMigrateCommand;

class MigrateCommand extends BaseMigrateCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:migrate:fort';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate Cortex Fort Tables.';
}

<?php

declare(strict_types=1);

namespace Cortex\Fort\Console\Commands;

use Rinvex\Fort\Console\Commands\MigrateCommand as BaseMigrateCommand;

class MigrateCommand extends BaseMigrateCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:migrate:fort';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate Cortex Fort Tables.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        parent::handle();

        $this->call('migrate', ['--step' => true, '--path' => 'app/cortex/fort/database/migrations']);
    }
}

Add missing migrations command handler

Add missing migrations command handler


<?php

namespace Yajra\Datatables\Contracts;

interface DataTableEngineContract
{
    /**
     * Get results
     *
     * @return mixed
     */
    public function results();

    /**
     * Count results
     *
     * @return integer
     */
    public function count();

    /**
     * Set auto filter off and run your own filter.
     * Overrides global search
     *
     * @param \Closure $callback
     * @return $this
     */
    public function filter(\Closure $callback);

    /**
     * Perform global search
     *
     * @return void
     */
    public function filtering();

    /**
     * Perform column search
     *
     * @return void
     */
    public function columnSearch();

    /**
     * Perform pagination
     *
     * @return void
     */
    public function paging();

    /**
     * Perform sorting of columns
     *
     * @return void
     */
    public function ordering();

    /**
     * Organizes works
     *
     * @param bool $mDataSupport
     * @return \Illuminate\Http\JsonResponse
     */
    public function make($mDataSupport = false);
}

<?php

namespace Yajra\Datatables\Contracts;

interface DataTableEngineContract
{
    /**
     * Get results
     *
     * @return mixed
     */
    public function results();

    /**
     * Count results
     *
     * @return integer
     */
    public function count();

    /**
     * Count total items.
     *
     * @return integer
     */
    public function totalCount();

    /**
     * Set auto filter off and run your own filter.
     * Overrides global search
     *
     * @param \Closure $callback
     * @return $this
     */
    public function filter(\Closure $callback);

    /**
     * Perform global search
     *
     * @return void
     */
    public function filtering();

    /**
     * Perform column search
     *
     * @return void
     */
    public function columnSearch();

    /**
     * Perform pagination
     *
     * @return void
     */
    public function paging();

    /**
     * Perform sorting of columns
     *
     * @return void
     */
    public function ordering();

    /**
     * Organizes works
     *
     * @param bool $mDataSupport
     * @return \Illuminate\Http\JsonResponse
     */
    public function make($mDataSupport = false);
}

Add totalCount on contact. Remove excess new line.


<?php

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\MongoDB\GridFSFile;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

class GH832Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
    /**
     * @expectedException MongoGridFSException
     */
    public function testGridFSWithUniqueIndex()
    {
        $this->dm->getSchemaManager()->ensureDocumentIndexes(GH832Document::CLASS);

        $docA = new GH832Document();
        $docA->unique = 'foo';
        $docA->file = new GridFSFile(__FILE__);

        $this->dm->persist($docA);
        $this->dm->flush();
        $this->dm->clear();

        $docB = new GH832Document();
        $docB->unique = 'foo';
        $docB->file = new GridFSFile(__FILE__);

        $this->dm->persist($docB);
        $this->dm->flush();
        $this->dm->clear();
    }
}

/** @ODM\Document */
class GH832Document
{
    const CLASSNAME = __CLASS__;

    /** @ODM\Id */
    public $id;

    /** @ODM\File */
    public $file;

    /**
     * @ODM\String
     * @ODM\UniqueIndex
     */
    public $unique;
}

<?php

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\MongoDB\GridFSFile;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

class GH832Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
    /**
     * @expectedException MongoGridFSException
     */
    public function testGridFSWithUniqueIndex()
    {
        $doc = new GH832Document();
        $this->dm->getSchemaManager()->ensureDocumentIndexes(get_class($doc));

        $docA = new GH832Document();
        $docA->unique = 'foo';
        $docA->file = new GridFSFile(__FILE__);

        $this->dm->persist($docA);
        $this->dm->flush();
        $this->dm->clear();

        $docB = new GH832Document();
        $docB->unique = 'foo';
        $docB->file = new GridFSFile(__FILE__);

        $this->dm->persist($docB);
        $this->dm->flush();
        $this->dm->clear();
    }
}

/** @ODM\Document */
class GH832Document
{
    const CLASSNAME = __CLASS__;

    /** @ODM\Id */
    public $id;

    /** @ODM\File */
    public $file;

    /**
     * @ODM\String
     * @ODM\UniqueIndex
     */
    public $unique;
}

Fix test for PHP 5.4

Fix test for PHP 5.4


<?php

if (class_exists('Block')) {

class TimelineBlock extends Block {

	private static $singular_name = 'Timeline Block';
	private static $plural_name = 'Timeline Blocks';

	private static $db = array(
		'ShowTaggedWith'		=> 'MultiValueField'
	);

	public function TimelineUrl() {
		Requirements::javascript('microblog/javascript/timeline-dashlet.js');
		$tags = $this->ShowTaggedWith->getValues();
		$extra = '';
		if (count($tags)) {
			$extra = '?tags=' . urlencode(implode(',', $tags));
		}
		return 'timeline' . $extra;
	}
}

}

<?php

if (class_exists('Block')) {

class TimelineBlock extends Block {

	private static $singular_name = 'Timeline Block';
	private static $plural_name = 'Timeline Blocks';

	private static $db = array(
		'ShowTaggedWith'		=> 'MultiValueField'
	);

	public function TimelineUrl() {
		TimelineController::include_microblog_requirements();
		Requirements::javascript('microblog/javascript/timeline-dashlet.js');
		$tags = $this->ShowTaggedWith->getValues();
		$extra = '';
		if (count($tags)) {
			$extra = '?tags=' . urlencode(implode(',', $tags));
		}
		return 'timeline' . $extra;
	}
}

}

FIX Include timeline requirements from block

To prevent load overhead when including the Timeline via ajax, include the
JS/css immediately on block load


<?php
namespace Craft;

class WeightedSearchPlugin extends BasePlugin
{
    function getName()
    {
        return 'Weighted Search';
    }

    function getVersion()
    {
        return '1.0';
    }

    function getDeveloper()
    {
        return 'WJA';
    }

    function getDeveloperUrl()
    {
        return 'http://wja.no/';
    }
}

<?php
namespace Craft;

class WeightedSearchPlugin extends BasePlugin
{
    function getName()
    {
        return 'Weighted Search';
    }

    function getVersion()
    {
        return '2.0';
    }

    function getDeveloper()
    {
        return 'WJA';
    }

    function getDeveloperUrl()
    {
        return 'http://wja.no/';
    }
}

Increase version number to 2.0

Increase version number to 2.0


#!/usr/bin/env php
<?php

/**
* set channel email notifications utility
* This is a preliminary solution using the existing functions from include/channel.php.
* More options would be nice.
**/

if(! file_exists('include/cli_startup.php')) {
    echo 'Run from the top level $Projectname web directory, as util/nconfig <args>' . PHP_EOL;
    exit(1);
}

require_once('include/cli_startup.php');
require_once('include/channel.php');

cli_startup();

	if($argc != 2) {
		echo 'Usage: util/nconfig channel_id|channel_address off|on' . PHP_EOL;
		exit(1);
	}

	if(ctype_digit($argv[1])) {
		$c = channelx_by_n($argv[1]);
	}
	else {
		$c = channelx_by_nick($argv[1]);
	}

	if(! $c) {
		echo t('Source channel not found.');
		exit(1);
	}

	switch ($argv[2]) {
		case 'off':
			$result = notifications_off($c['channel_id']);
			break;
		case 'on':
			$result = notifications_on($c['channel_id']);
			break;
		default:
			echo 'Only on or off in lower cases are allowed' . PHP_EOL;
			exit(1);
	}

	if($result['success'] == false) {
		echo $result['message'];
		exit(1);
	}

	exit(0);

#!/usr/bin/env php
<?php

/**
* switch off channel email notifications utility
* This is a preliminary solution using the existing functions from include/channel.php.
* More options would be nice.
**/

if(! file_exists('include/cli_startup.php')) {
    echo 'Run from the top level $Projectname web directory, as util/nconfig <args>' . PHP_EOL;
    exit(1);
}

require_once('include/cli_startup.php');
require_once('include/channel.php');

cli_startup();

	if($argc != 2) {
		echo 'Usage: util/nconfig channel_id|channel_address off' . PHP_EOL;
		exit(1);
	}

	if(ctype_digit($argv[1])) {
		$c = channelx_by_n($argv[1]);
	}
	else {
		$c = channelx_by_nick($argv[1]);
	}

	if(! $c) {
		echo t('Source channel not found.');
		exit(1);
	}

	switch ($argv[2]) {
		case 'off':
			$result = notifications_off($c['channel_id']);
			break;
		default:
			echo 'Only on or off in lower cases are allowed' . PHP_EOL;
			exit(1);
	}

	if($result['success'] == false) {
		echo $result['message'];
		exit(1);
	}

	exit(0);

Drop on switch for notifications

Drop on switch for notifications


<?php

namespace fennecweb\ajax\listing;

use \fennecweb\WebService as WebService;

class TraitsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test for error returned by user is not logged in
        list($service) = WebService::factory('listing/Traits');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '')));
        $expected = array(
            array(
                "name" => "PlantHabit",
                "trait_type_id" => 1,
                "frequency" => 48916
            )
        );
        $this->assertArraySubset($expected, $results);
    }
}

<?php

namespace fennecweb\ajax\listing;

use \fennecweb\WebService as WebService;

class TraitsTest extends \PHPUnit_Framework_TestCase
{

    public function testExecute()
    {
        //Test for traits without search term or limit
        list($service) = WebService::factory('listing/Traits');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '')));
        $expected = array(
            array(
                "name" => "PlantHabit",
                "trait_type_id" => 1,
                "frequency" => 48916
            )
        );
        $this->assertEquals($expected, $results);
    }
}

Fix test for Traits listing

Fix test for Traits listing


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Views;

use GrottoPress\Jentil\Setups\AbstractSetup;

final class Archive extends AbstractSetup
{
    public function run()
    {
        \add_action('jentil_before_content', [$this, 'renderDescription']);
    }

    /**
     * @action jentil_before_content
     */
    public function renderDescription()
    {
        $page = $this->app->utilities->page;

        if (!$page->is('archive')) {
            return;
        }

        if (!($description = $page->description())) {
            return;
        }

        echo '
'.
            $description.
        '
';
    }
}

<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Views;

use GrottoPress\Jentil\Setups\AbstractSetup;

final class Archive extends AbstractSetup
{
    public function run()
    {
        \add_action('jentil_after_title', [$this, 'renderDescription']);
    }

    /**
     * @action jentil_after_title
     */
    public function renderDescription()
    {
        $page = $this->app->utilities->page;

        if (!$page->is('archive')) {
            return;
        }

        if (!($description = $page->description())) {
            return;
        }

        echo '
'.
            $description.
        '
';
    }
}

Move archive description into page header


<?php

class Session_helper {

	function set($key, $val)
	{
		$_SESSION["$key"] = $val;
	}

	function get($key)
	{
		return $_SESSION["$key"];
	}

	function destroy()
	{
		session_destroy();
	}

	function getCurrentUserLogin()
	{
		if (array_key_exists('user-login', $_SESSION))
		{
			return $_SESSION['user-login'];
		}
		else
		{
			return null;
		}
	}

}

?>

<?php

class Session_helper {

	function set($key, $val)
	{
		$_SESSION["$key"] = $val;
	}

	function get($key)
	{
		if (array_key_exists("$key", $_SESSION))
		{
			return $_SESSION["$key"];
		}
		return null;
	}

	function destroy()
	{
		session_destroy();
	}

	function getCurrentUserLogin()
	{
		if (array_key_exists('user-login', $_SESSION))
		{
			return $_SESSION['user-login'];
		}
		else
		{
			return null;
		}
	}

}

?>

Check the existence of the key in Session_helper->get and returns null if the key does not exist.


<div class="campaign-result <?php print $modifier_classes ?>">
  <?php if($staff_pick) { ?>

Staff Pick

  <?php } ?>
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=" data-src="<?php print $image ?>">

<?php print $title; ?>

<?php print $cta; ?>

  <?php print $link; ?>

<div class="campaign-result <?php print $modifier_classes ?>">
  <?php if($staff_pick) { ?>

Staff Pick

  <?php } ?>
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=" data-src="<?php print $image ?>" alt="<?php print $title; ?>">

<?php print $title; ?>

<?php print $cta; ?>

  <?php print $link; ?>

Add alt tags to homepage thumbnail images.


<?php

declare(strict_types=1);

namespace League\Flysystem\Ftp;

use League\Flysystem\FilesystemAdapter;

/**
 * @group ftp
 */
class FtpAdapterTest extends FtpAdapterTestCase
{
    protected static function createFilesystemAdapter(): FilesystemAdapter
    {
        $options = FtpConnectionOptions::fromArray([
           'host' => 'localhost',
           'port' => 2121,
           'timestampsOnUnixListingsEnabled' => true,
           'root' => '/home/foo/upload/',
           'username' => 'foo',
           'password' => 'pass',
       ]);

        static::$connectivityChecker = new ConnectivityCheckerThatCanFail(new NoopCommandConnectivityChecker());

        return new FtpAdapter($options, null, static::$connectivityChecker);
    }

    /**
     * @test
     */
    public function disconnect_after_destruct(): void
    {
        /** @var FtpAdapter $adapter */
        $adapter = $this->adapter();
        $reflection = new \ReflectionObject($adapter);
        $adapter->fileExists('foo.txt');
        $reflectionProperty = $reflection->getProperty('connection');
        $reflectionProperty->setAccessible(true);
        $connection = $reflectionProperty->getValue($adapter);
        unset($reflection);

        $this->assertTrue(false !== ftp_pwd($connection));
        unset($adapter);
        static::clearFilesystemAdapterCache();
        $this->assertFalse(@ftp_pwd($connection));
    }
}

<?php

declare(strict_types=1);

namespace League\Flysystem\Ftp;

use League\Flysystem\FilesystemAdapter;

/**
 * @group ftp
 */
class FtpAdapterTest extends FtpAdapterTestCase
{
    protected static function createFilesystemAdapter(): FilesystemAdapter
    {
        $options = FtpConnectionOptions::fromArray([
           'host' => 'localhost',
           'port' => 2121,
           'timestampsOnUnixListingsEnabled' => true,
           'root' => '/home/foo/upload/',
           'username' => 'foo',
           'password' => 'pass',
       ]);

        static::$connectivityChecker = new ConnectivityCheckerThatCanFail(new NoopCommandConnectivityChecker());

        return new FtpAdapter($options, null, static::$connectivityChecker);
    }

    /**
     * @test
     */
    public function disconnect_after_destruct(): void
    {
        /** @var FtpAdapter $adapter */
        $adapter = $this->adapter();
        $reflection = new \ReflectionObject($adapter);
        $adapter->fileExists('foo.txt');
        $reflectionProperty = $reflection->getProperty('connection');
        $reflectionProperty->setAccessible(true);
        $connection = $reflectionProperty->getValue($adapter);
        unset($reflection);

        $this->assertTrue(false !== ftp_pwd($connection));
        unset($adapter);
        static::clearFilesystemAdapterCache();
        $this->assertFalse((new NoopCommandConnectivityChecker())->isConnected($connection));
    }
}

Use connection check in test

Use connection check in test


<?PHP

/**
 *  A common interface for all value objects.
 *
 *
 *  @author      Adamo Crespi <hello@aerendir.me>
 *  @copyright   Copyright (c) 2015, Adamo Crespi
 *  @license     MIT License
 */
namespace SerendipityHQ\Component\ValueObjects\Common;

/**
 * Defines the minimum requisites of Value Objects.
 */
interface ValueObjectInterface
{
    /**
     * The string representation of the object.
     *
     * @return string
     */
    public function __toString();

    /**
     * Disable the __set magic method.
     *
     * Implement this way:
     *
     *     public function __set($field, $value)
     *     {
     *         // Body MUST BE EMPTY
     *     }
     *
     * @param mixed $field
     * @param mixed $value
     */
    public function __set($field, $value);
}

<?PHP

/**
 *  A common interface for all value objects.
 *
 *
 *  @author      Adamo Crespi <hello@aerendir.me>
 *  @copyright   Copyright (c) 2015, Adamo Crespi
 *  @license     MIT License
 */
namespace SerendipityHQ\Component\ValueObjects\Common;

/**
 * Defines the minimum requisites of Value Objects.
 */
interface ValueObjectInterface
{
    /**
     * The string representation of the object.
     *
     * This method can accept options to refine the string returned.
     *
     * @return string
     */
    public function toString(array $options = []);

    /**
     * The string representation of the object.
     *
     * @return string
     */
    public function __toString();

    /**
     * Disable the __set magic method.
     *
     * Implement this way:
     *
     *     public function __set($field, $value)
     *     {
     *         // Body MUST BE EMPTY
     *     }
     *
     * @param mixed $field
     * @param mixed $value
     */
    public function __set($field, $value);
}

Feature: Add a `toString()` method that can accept options.


<?php

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

namespace JsonSchema\Constraints;

/**
 * The Enum Constraints, validates an element against a given set of possibilities
 *
 * @author Robert Schönthal <seroscho@googlemail.com>
 * @author Bruno Prieto Reis <bruno.p.reis@gmail.com>
 */
class Enum extends Constraint
{
    /**
     * {@inheritDoc}
     */
    public function check($element, $schema = null, $path = null, $i = null)
    {
        if (!in_array($element, $schema->enum)) {
            $this->addError($path, "does not have a value in the enumeration " . implode(', ', $schema->enum));
        }
    }
}

<?php

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

namespace JsonSchema\Constraints;

/**
 * The Enum Constraints, validates an element against a given set of possibilities
 *
 * @author Robert Schönthal <seroscho@googlemail.com>
 * @author Bruno Prieto Reis <bruno.p.reis@gmail.com>
 */
class Enum extends Constraint
{
    /**
     * {@inheritDoc}
     */
    public function check($element, $schema = null, $path = null, $i = null)
    {
        // Only validate enum if the attribute exists
        if ($element instanceof Undefined && (!isset($schema->required) || !$schema->required))  {
            return;
        }

        if (!in_array($element, $schema->enum)) {
            $this->addError($path, "does not have a value in the enumeration " . implode(', ', $schema->enum));
        }
    }
}

Add support for optional enums

Add support for optional enums


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Customizer\Title\Settings;

use GrottoPress\Jentil\Setups\Customizer\Title\Title;
use GrottoPress\Jentil\Utilities\ThemeMods\Title as TitleMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;

abstract class AbstractSetting extends Setting
{
    /**
     * @var TitleMod
     */
    protected $mod;

    public function __construct(Title $title)
    {
        parent::__construct($title);

        $this->args['transport'] = 'postMessage';
        $this->args['sanitize_callback'] = 'wp_kses_data';

        $this->control['section'] = $this->section->id;
        $this->control['label'] = \esc_html__('Enter title', 'jentil');
        $this->control['type'] = 'text';
    }

    protected function themeMod(array $args): TitleMod
    {
        return $this->section->customizer->app->utilities->themeMods->title(
            $args
        );
    }
}

<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Customizer\Title\Settings;

use GrottoPress\Jentil\Setups\Customizer\Title\Title;
use GrottoPress\Jentil\Utilities\ThemeMods\Title as TitleMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;

abstract class AbstractSetting extends Setting
{
    /**
     * @var TitleMod
     */
    protected $mod;

    public function __construct(Title $title)
    {
        parent::__construct($title);

        $this->args['transport'] = 'refresh';
        $this->args['sanitize_callback'] = 'wp_kses_data';

        $this->control['section'] = $this->section->id;
        $this->control['label'] = \esc_html__('Enter title', 'jentil');
        $this->control['type'] = 'text';
    }

    protected function themeMod(array $args): TitleMod
    {
        return $this->section->customizer->app->utilities->themeMods->title(
            $args
        );
    }
}

Use 'refresh' for title customizer settings transport

'postMessage' is buggy as page-specific functions return empty in
the customizer and so JS cannot replace short tags.

Will work out a way to do this later.


<?php

namespace SLLH\IsoCodesValidatorBundle\Tests\DependencyInjection\Compiler;

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase;
use SLLH\IsoCodesValidatorBundle\DependencyInjection\Compiler\TranslationPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class TranslationPassTest extends AbstractCompilerPassTestCase
{
    protected function registerCompilerPass(ContainerBuilder $container)
    {
        $container->addCompilerPass(new TranslationPass());
    }
}

<?php

namespace SLLH\IsoCodesValidatorBundle\Tests\DependencyInjection\Compiler;

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase;
use SLLH\IsoCodesValidatorBundle\DependencyInjection\Compiler\TranslationPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class TranslationPassTest extends AbstractCompilerPassTestCase
{
    protected function registerCompilerPass(ContainerBuilder $container)
    {
        $container->addCompilerPass(new TranslationPass());
    }

    public function testWithTranslatorService()
    {
        $this->registerService('translator.default', 'Symfony\Bundle\FrameworkBundle\Translation\Translator');
        $this->compile();

        // TODO: Check if translations resources are correctly added to the translator service.
    }
}

Test TranslationPass compile with translator.default definition


    <input type="text" id="name"
                class="form-control input-lg"
                name="name"
                placeholder="Enter Page Title"
                value="{{ old('name', $page->name) }}">

                Link:

            {{ url() }}/

        <input type="text" class="form-control" name="slug" value="{{ old('slug', $page->slug) }}" readonly>

                Edit

        @if ($page->link)

            link) }}" class="btn btn-default btn-flat">
                View Page

        @endif

    <input type="text" id="name"
                class="form-control input-lg"
                name="name"
                placeholder="Enter Page Title"
                value="{{ old('name', $page->name) }}">

                Link:

            {{ url() }}/

        <input type="text" class="form-control" name="slug" value="{{ old('slug', $page->slug) }}" readonly>

                Edit

        @if ($page->link && !$page->trashed())

            link) }}" class="btn btn-default btn-flat">
                View Page

        @endif

Remove link for trashed pages from title-and-slug section aswell


<?php

namespace AppBundle\ShowUnusedPhpFiles;

/**
 * Tests for the CommonPathDeterminator.
 */
final class CommonPathDeterminatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function returnsEmptyStringForEmptyInput()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath([]);
        $this->assertInternalType('string', $result);
        $this->assertEmpty($result);
    }

    /**
     * @test
     */
    public function returnsEmptyStringIfNoCommonPath()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath(['abc', 'def']);
        $this->assertInternalType('string', $result);
        $this->assertEmpty($result);
    }

    /**
     * @test
     */
    public function returnsCommonPath()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath(['/var/a', '/var/b']);
        $this->assertInternalType('string', $result);
        $this->assertEquals('/var', $result);
    }

    /**
     * @test
     */
    public function returnsCommonPathAndIsNotTrickedByCommonFileName()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath(['/var/common-1', '/var/common-2']);
        $this->assertInternalType('string', $result);
        $this->assertEquals('/var', $result);
    }
}

<?php

namespace AppBundle\ShowUnusedPhpFiles;

/**
 * Tests for the CommonPathDeterminator.
 */
final class CommonPathDeterminatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function returnsEmptyStringForEmptyInput()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath([]);
        $this->assertInternalType('string', $result);
        $this->assertEmpty($result);
    }

    /**
     * @test
     */
    public function returnsEmptyStringIfNoCommonPath()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath(['abc', 'def']);
        $this->assertInternalType('string', $result);
        $this->assertEmpty($result);
    }

    /**
     * @test
     */
    public function returnsCommonPath()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath([__DIR__ . '/fixtures/ignored', __DIR__ . '/fixtures/used']);
        $this->assertInternalType('string', $result);
        $this->assertEquals(__DIR__ . '/fixtures', $result);
    }

    /**
     * @test
     */
    public function returnsCommonPathAndIsNotTrickedByCommonFileName()
    {
        $result = (new CommonPathDeterminator())->determineCommonPath([__DIR__ . '/fixtures/common-1', __DIR__ . '/fixtures/common-2']);
        $this->assertInternalType('string', $result);
        $this->assertEquals(__DIR__ . '/fixtures', $result);
    }
}

Fix test paths on Mac OS

Fix test paths on Mac OS


<?php

namespace ModelForm\Test;

use ModelForm\Fields\CharField;
use ModelForm\Form;

class FieldsTest extends TestCase
{
    public function testCreateField()
    {
        $form = new Form();
        $form->name = new CharField(['label'=>'Testing']);

        $this->assertEquals('name', $form->name->name);
        $this->assertEquals($form, $form->name->form);
        $this->assertEquals('Testing', $form->name->label);
    }
}

<?php

namespace ModelForm\Test;

use ModelForm\Fields\CharField;
use ModelForm\Form;

class FieldsTest extends TestCase
{
    public function testFieldAcceptNameAndLabel()
    {
        $form = new Form();
        $form->name = new CharField(['label'=>'Testing']);
        $this->assertEquals('name', $form->name->name);
        $this->assertEquals($form, $form->name->form);
        $this->assertEquals('Testing', $form->name->label);
    }

    public function testFieldRenderHtmlOptions() {
        $form = new Form();
        $form->description = new CharField(['label'=>'Description']);
        $htmlOptions = [
            'maxlength' => 10,
        ];
        $this->assertEquals(
            '<input maxlength="10" name="Form-description" type="text">',
            $form->description->text($htmlOptions)
        );
    }
}

Test field render html options

Test field render html options


<?php if ( SubfolioFiles::have_features() ) : ?>

			<?php foreach ( SubfolioFiles::features() as $feature) : ?>

				  <a href="<?php echo $feature['link'] ?>">
			    	<img src="<?php echo $feature['image_file'] ?>">

<?php echo $feature['title'] ?>

<?php echo $feature['description'] ?>

			<?php endforeach; ?>

<?php endif; ?>

<?php if ( SubfolioFiles::have_features() ) : ?>

			<?php foreach ( SubfolioFiles::features() as $feature) : ?>

				  <a href="<?php echo $feature['link'] ?>" style="width: <?php echo $feature['image_width'] ?>px">
			    	<img src="<?php echo $feature['image_file'] ?>" width="<?php echo $feature['image_width'] ?>px" height="<?php echo $feature['image_height'] ?>px">

<?php echo $feature['title'] ?>

<?php echo $feature['description'] ?>

			<?php endforeach; ?>

<?php endif; ?>

Set the width of the feature text to go with the new feature design


<?php

namespace Math\Functions;

class PolynomialTest extends \PHPUnit_Framework_TestCase
{
    public function testString()
    {
        // p(x) = x² + 2x + 3

        $polynomial = new Polynomial([1, 2, 3]);
        $expected = " x² + 2x + 3";
        $actual = strval($polynomial);
        $this->assertEquals($expected, $actual);
    }

    public function testEval()
    {
        // p(x) = x² + 2x + 3
        // p(0) = 3

        $polynomial = new Polynomial([1, 2, 3]);
        $expected = 3;
        $actual = $polynomial(0);
        $this->assertEquals($expected, $actual);
    }
}

<?php

namespace Math\Functions;

class PolynomialTest extends \PHPUnit_Framework_TestCase
{
    public function testString()
    {
        // p(x) = x² + 2x + 3

        $polynomial = new Polynomial([1, 2, 3]);
        $expected = " x² + 2x + 3";
        $actual = strval($polynomial);
        $this->assertEquals($expected, $actual);
    }

    /**
     * @dataProvider dataProviderForEval
     */
    public function testEval(array $coefficients, $x, $expected)
    {
        $polynomial = new Polynomial($coefficients);
        $evaluated  = $polynomial($x);
        $this->assertEquals($expected, $evaluated);
    }

    public function dataProviderForEval()
    {
        return [
            [
                [1, 2, 3], // p(x) = x² + 2x + 3
                0, 3       // p(0) = 3
            ],
            [
                [1, 2, 3], // p(x) = x² + 2x + 3
                1, 6       // p(1) = 6
            ],
            [
                [1, 2, 3], // p(x) = x² + 2x + 3
                2, 11      // p(2) = 11
            ],
            [
                [1, 2, 3], // p(x) = x² + 2x + 3
                3, 18      // p(3) = 18
            ],
            [
                [1, 2, 3], // p(x) = x² + 2x + 3
                4, 27      // p(4) = 27
            ],
            [
                [1, 2, 3], // p(x) = x² + 2x + 3
                -1, 2     // p(-1) = 2
            ],
        ];
    }
}

Refactor Polynomial unit test and add more test cases.


<?php

namespace Sirius\Validation\Rule;

use Sirius\Validation\Rule\GreaterThan as Rule;

class GreaterThanTest extends \PHPUnit_Framework_TestCase
{

    function setUp()
    {
        $this->rule = new Rule();
    }

    function testDefaultOptions()
    {
        $this->assertNull($this->rule->getOption('min'));
        $this->assertTrue($this->rule->getOption('inclusive'));
    }

    function testExclusiveValidation()
    {
        $this->rule->setOption('inclusive', false);
        $this->rule->setOption('min', 100);
        $this->assertFalse($this->rule->validate(100));
    }

    function testValidationWithoutALimit()
    {
        $this->assertTrue($this->rule->validate(0));
    }

    function testConstructCvsFormatMinZeroAndInclusiveFalse()
    {
        $this->rule = new Rule('0,false');
        $this->assertSame('0', $this->rule->getOption('min'));
        $this->assertSame(false, $this->rule->getOption('inclusive'));
    }
}

<?php

namespace Sirius\Validation\Rule;

use Sirius\Validation\Rule\GreaterThan as Rule;

class GreaterThanTest extends \PHPUnit_Framework_TestCase
{

    function setUp()
    {
        $this->rule = new Rule();
    }

    function testDefaultOptions()
    {
        $this->assertNull($this->rule->getOption('min'));
        $this->assertTrue($this->rule->getOption('inclusive'));
    }

    function testExclusiveValidation()
    {
        $this->rule->setOption('inclusive', false);
        $this->rule->setOption('min', 100);
        $this->assertFalse($this->rule->validate(100));
    }

    function testValidationWithoutALimit()
    {
        $this->assertTrue($this->rule->validate(0));
    }

    function testConstructCvsFormatMinZeroAndInclusiveFalse()
    {
        $this->rule = new Rule('0,false');
        $this->assertSame('0', $this->rule->getOption('min'));
        $this->assertSame(false, $this->rule->getOption('inclusive'));
    }

    function testConstructWithMinValueZeroQueryStringFormat()
    {
        $this->rule = new Rule('min=0');
        $this->assertSame('0', $this->rule->getOption('min'));
    }
}

Add test to check query string format with one option


<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_top_files_info()
{
	return array(
		'name' => tra('Top files'),
		'description' => tra('Displays the specified number of files with links to them, starting with the one with most hits.'),
		'prefs' => array('feature_file_galleries'),
		'params' => array(),
		'common_params' => array('nonums', 'rows')
	);
}

function module_top_files($mod_reference, $module_params)
{
	global $smarty;
	$filegallib = TikiLib::lib('filegal');
	$ranking = $filegallib->list_files(0, $mod_reference["rows"], 'hits_desc', '');

	$smarty->assign('modTopFiles', $ranking["data"]);
}

<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_top_files_info()
{
	return array(
		'name' => tra('Top Files'),
		'description' => tra('Displays the specified number of files with links to them, starting with the one with most hits.'),
		'prefs' => array('feature_file_galleries'),
		'params' => array(),
		'common_params' => array('nonums', 'rows')
	);
}

function module_top_files($mod_reference, $module_params)
{
	global $smarty;
	$filegallib = TikiLib::lib('filegal');
	$ranking = $filegallib->list_files(0, $mod_reference["rows"], 'hits_desc', '');

	$smarty->assign('modTopFiles', $ranking["data"]);
}

Tidy up info a little for the PluginModule popup edit form

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


<?php
require_once 'vendor/autoload.php';

use \Michelf\Markdown;

/**
 * Class Converter
 *
 * An Sir Trevor to HTML conversion helper for PHP
 *
 * @version 1.0.0
 * @author Wouter Sioen <info@woutersioen.be>
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 */
class Converter
{
	/**
	 * Converts the outputted json from Sir Trevor to html
	 *
	 * @param string $json
	 * @return string html
	 */
	public function toHtml($json)
	{

	}

	/**
	 * @param string $text
	 * @return string $html
	 */
	public function defaultToHtml($text)
	{
		return Markdown::defaultTransform($text);
	}
}

Use spaces as indentation to make the class more psr-0 compatible


<?php
/**
 * shipping_patch_0360
 * @package modules.shipping
 */
class shipping_patch_0360 extends patch_BasePatch
{
//  by default, isCodePatch() returns false.
//  decomment the following if your patch modify code instead of the database structure or content.
    /**
     * Returns true if the patch modify code that is versionned.
     * If your patch modify code that is versionned AND database structure or content,
     * you must split it into two different patches.
     * @return Boolean true if the patch modify code that is versionned.
     */
//	public function isCodePatch()
//	{
//		return true;
//	}

	/**
	 * Entry point of the patch execution.
	 */
	public function execute()
	{
        $this->executeXmlScript('init.xml');
	}
}

<?php
/**
 * shipping_patch_0360
 * @package modules.shipping
 */
class shipping_patch_0360 extends patch_BasePatch
{
//  by default, isCodePatch() returns false.
//  decomment the following if your patch modify code instead of the database structure or content.
    /**
     * Returns true if the patch modify code that is versionned.
     * If your patch modify code that is versionned AND database structure or content,
     * you must split it into two different patches.
     * @return Boolean true if the patch modify code that is versionned.
     */
//	public function isCodePatch()
//	{
//		return true;
//	}

	/**
	 * Entry point of the patch execution.
	 */
	public function execute()
	{
        $this->executeModuleScript('init.xml', 'shipping');
	}
}

[UPDATE] Add a filter on shipping modes, fix the importa of the dynamic list


<?php

use H4D\Leveret\Application;
use H4D\Leveret\Validation\Adapters\H4DConstraintAdapter;
use H4D\Validator\Constraints\Enum;

require_once(__DIR__.'/../../vendor/autoload.php');

$app = new Application();
$app->registerRoute('GET', '/hello/:(string)name')
    ->addRequestConstraints('name', new H4DConstraintAdapter((new Enum())->setOptions(['paco', 'maria'])))
    ->setAction(
        function ($name) use ($app)
        {
            $isValid = $app->isValidRequest();
            if (!$isValid)
            {
                throw new \Exception($app->getRequestConstraintsViolationMessagesAsString());
            }
            $app->getResponse()->setBody('Hello '.$name);
        });
$app->run();

<?php

use H4D\Leveret\Application;
use H4D\Leveret\Validation\Adapters\H4DConstraintAdapter;
use H4D\Leveret\Validation\Adapters\SymfonyConstraintAdapter;
use H4D\Validator\Constraints\Enum;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Required;

require_once(__DIR__.'/../../vendor/autoload.php');

$app = new Application();
$app->registerRoute('GET', '/hello/:(string)name')
    ->addRequestConstraints('name', new H4DConstraintAdapter((new Enum())->setOptions(['paco', 'maria'])))
    ->setAction(
        function ($name) use ($app)
        {
            $isValid = $app->isValidRequest();
            if (!$isValid)
            {
                throw new \Exception($app->getRequestConstraintsViolationMessagesAsString());
            }
            $app->getResponse()->setBody('Hello '.$name);
        });

$app->registerRoute('GET', '/bye/:(string)name')
    ->addRequestConstraints('name', [new SymfonyConstraintAdapter(new Required()),
                                     new SymfonyConstraintAdapter(new NotBlank()),
                                     new SymfonyConstraintAdapter(new Length(array('min'=>3,
                                                                                'max'=>10)))])
    ->setAction(
        function ($name) use ($app)
        {
            $isValid = $app->isValidRequest();
            if (!$isValid)
            {
                throw new \Exception($app->getRequestConstraintsViolationMessagesAsString());
            }
            $app->getResponse()->setBody('Hello '.$name);
        });

$app->run();

Update test with symfony constraints adapter usage.


<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Templates Toolbar Class
 *
 * @author      Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 */
class ComTemplatesControllerToolbarTemplate extends ComDefaultControllerToolbarDefault
{
    public function __construct(KConfig $config)
    {
        parent::__construct($config);

        $this->addSeperator()
             ->addPreview();
    }

    protected function _commandPreview(KControllerToolbarCommand $command)
    {
        $state = $this->getController()->getModel()->getState();

        $template = $state->name;
        $base     = $state->application == 'site' ? JURI::root() : JURI::base();

        $command->append(array(
            'width'   => '640',
            'height'  => '480',
        ))->append(array(
            'attribs' => array(
                'href' 	 =>  $base.'index.php?tp=1&template='.$template,
                'target' => 'preview'
            )
        ));
    }
}

<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Templates Toolbar Class
 *
 * @author      Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 */
class ComTemplatesControllerToolbarTemplate extends ComDefaultControllerToolbarDefault
{
    public function getCommands()
    {
        $this->addSeperator()
             ->addPreview();

        return parent::getCommands();
    }

    protected function _commandPreview(KControllerToolbarCommand $command)
    {
        $state = $this->getController()->getModel()->getState();

        $template = $state->name;
        $base     = $state->application == 'site' ? JURI::root() : JURI::base();

        $command->append(array(
            'width'   => '640',
            'height'  => '480',
        ))->append(array(
            'attribs' => array(
                'href' 	 =>  $base.'index.php?tp=1&template='.$template,
                'target' => 'preview'
            )
        ));
    }
}

Insert custom commands through the getCommands() function.


<?php

namespace Coyote\Http\Controllers\User;

class UserApiController extends BaseController
{
    /**
    * @param \Coyote\User $user
    */
    public function get($user)
    {
        return response()->json([
            'id' => $user->id,
            'name' => $user->name,
        ]);
    }
}

<?php

namespace Coyote\Http\Controllers\User;

class UserApiController extends BaseController
{
    public function __construct()
    {
    }

    /**
    * @param \Coyote\User $user
    */
    public function get($user)
    {
        return response()->json([
            'id' => $user->id,
            'name' => $user->name,
        ]);
    }
}

Add empty constructor, as advised by Adam


<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),

        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

Add bundles to the kernel

Add bundles to the kernel


<?php
namespace GuzzleHttp\Exception;

interface GuzzleException {}

<?php
namespace GuzzleHttp\Exception;

/**
 * @method string getMessage()
 * @method \Throwable|null getPrevious()
 * @method mixed getCode()
 * @method string getFile()
 * @method int getLine()
 * @method array getTrace()
 * @method string getTraceAsString()
 */
interface GuzzleException {}

Add annotations for exception methods

Add annotations for exception methods


<?php

namespace ValueObjects\Base;

use ValueObjects\ValueObject;

/**
 * Class Strings
 * ValueObject that represents a String with lots of useful methods.
 * It is called string since string is a reserved word in Php 7.
 * @package ValueObjects\Base
 */
class Strings extends ValueObject
{
    public function __construct(string $value)
    {
        parent::__construct($value);
    }

    /**
     * Creates a string from an integer.
     * @param $int
     * @return Strings
     */
    public static function fromInt(int $int)
    {
        return new self((string) $int);
    }

    /**
     * Cretes a string from a double.
     * @param float $double
     * @return Strings
     */
    public static function fromFloat(float $double)
    {
        return new static((string) $double);
    }

    /**
     * Returns a new string converted to uppercase.
     * @return self
     */
    public function toUpperCase()
    {
        return new static(strtoupper($this->value));
    }

    /**
     * Returns a new string converted to low case.
     * @return self
     */
    public function toLowerCase()
    {
        return new static(strtolower($this->value));
    }

    public function trim()
    {
        return new static(trim($this->value));
    }

    public function length(): int
    {
        return strlen($this->value);
    }
}

<?php

namespace ValueObjects\Base;

use ValueObjects\ValueObject;

/**
 * Class Strings
 * ValueObject that represents a String with lots of useful methods.
 * It is called string since string is a reserved word in Php 7.
 * @package ValueObjects\Base
 */
class Strings extends ValueObject
{
    public function __construct(string $value)
    {
        parent::__construct($value);
    }

    /**
     * Creates a string from an integer.
     * @param $int
     * @return Strings
     */
    public static function fromInt(int $int)
    {
        return new self((string) $int);
    }

    /**
     * Cretes a string from a double.
     * @param float $double
     * @return Strings
     */
    public static function fromFloat(float $double)
    {
        return new static((string) $double);
    }

    /**
     * Returns a new string converted to uppercase.
     * @return self
     */
    public function toUpperCase()
    {
        return new static(strtoupper($this->value));
    }

    /**
     * Returns a new string converted to low case.
     * @return self
     */
    public function toLowerCase()
    {
        return new static(strtolower($this->value));
    }

    /**
     * Returns a new trimmed string.
     * @return self
     */
    public function trim(): self
    {
        return new static(trim($this->value));
    }

    /**
     * Returns the length of a string.
     * @return int
     */
    public function length(): int
    {
        return strlen($this->value);
    }
}

Add documentation to the method.

Add documentation to the method.


<?php session_start(); ?>
<!DOCTYPE html>

<head>
	<title>ClinicCases - Online Case Management Software for Law School Clinics</title>
	<meta name="robots" content="noindex">
	<link rel="stylesheet" href="html/css/cm.css" type="text/css">
	<link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css">
	<link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css">
	<link rel="shortcut icon" type="image/x-icon" href="html/images/favicon.ico">

	<script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script>
	<script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script>
	<script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script>
	<script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>

	<script src="html/js/sizeContentWindow.js" type="text/javascript"></script>

Add js resize script to header.

Add js resize script to header.

git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@901 54a900ba-8191-11dd-a5c9-f1483cedc3eb


@extends('layouts.app')

@section('fonts')
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
@endsection

@section('content')
        @if (Auth::check())

	                			Incidents

	                			Schedule

	                			City Email

        @else
            @include('auth.login');
        @endif
@endsection

Update links to external resources on homepage


<?php
namespace BackupCli\Commands;

use BackupCli\Config;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ProfileListDb extends Command
{

    protected function configure()
    {
        $this->setName('profile:listdb')->setDescription('Lists all the existing database profiles.');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Database data.
        $databases = Config::getFile('database');
        foreach ($databases as $profile => $data) {
            $dbs[] = [$profile, $data['type'], $data['database'], $data['user'], $data['pass'], $data['host'], $data['port']];
        }

        // Output table.
        $table = new Table($output);
        $table->setHeaders(['Profile', 'Type', 'Database', 'Username', 'Password', 'Server', 'Port'])->setRows($dbs);
        $table->render();
    }

}

<?php
namespace BackupCli\Commands;

use BackupCli\Config;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ProfileListDb extends Command
{

    protected function configure()
    {
        $this->setName('profile:listdb')->setDescription('Lists all the existing database profiles.');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Database data.
        $databases = Config::getFile('database');
        foreach ($databases as $profile => $data) {
            $dbs[] = [$profile, $data['type'], $data['database'], $data['user'], $data['host'], $data['port']];
        }

        // Output table.
        $table = new Table($output);
        $table->setHeaders(['Profile', 'Type', 'Database', 'Username', 'Server', 'Port'])->setRows($dbs);
        $table->render();
    }

}

Remove password from 'listdb' command

Remove password from 'listdb' command


<?php

namespace Kula\HEd\Bundle\SchedulingBundle\Controller;

use Kula\Core\Bundle\FrameworkBundle\Controller\Controller;

class CoreRoomsController extends Controller {

  public function indexAction() {
    $this->authorize();
    $this->processForm();
    $this->setRecordType('Core.Organization.School.Term', null,
    array('CORE_ORGANIZATION_TERMS' =>
      array('ORGANIZATION_ID' => $this->focus->getSchoolIDs(),
            'TERM_ID' => $this->focus->getTermID()
           )
         )
    );
    $rooms = array();
    if ($this->record->getSelectedRecordID()) {

      // Get Rooms
      $rooms = $this->db()->db_select('STUD_ROOM')
        ->fields('STUD_ROOM')
        ->condition('ORGANIZATION_TERM_ID', $this->record->getSelectedRecordID())
        ->orderBy('ROOM_NUMBER', 'ASC')
        ->execute()->fetchAll();

    }

    return $this->render('KulaHEdSchedulingBundle:CoreRooms:index.html.twig', array('rooms' => $rooms));

  }

  public function chooserAction() {
    $this->authorize();
    $data = $this->chooser('HEd.Room')->createChooserMenu($this->request->query->get('q'));
    return $this->JSONResponse($data);
  }

}

<?php

namespace Kula\HEd\Bundle\SchedulingBundle\Controller;

use Kula\Core\Bundle\FrameworkBundle\Controller\Controller;

class CoreRoomsController extends Controller {

  public function indexAction() {
    $this->authorize();
    $this->processForm();
    $this->setRecordType('Core.Organization.School.Term', null,
    array('Core.Organization.Term' =>
      array('Core.Organization.Term.OrganizationID' => $this->focus->getSchoolIDs(),
            'Core.Organization.Term.TermID' => $this->focus->getTermID()
           )
         )
    );
    $rooms = array();
    if ($this->record->getSelectedRecordID()) {

      // Get Rooms
      $rooms = $this->db()->db_select('STUD_ROOM')
        ->fields('STUD_ROOM')
        ->condition('ORGANIZATION_TERM_ID', $this->record->getSelectedRecordID())
        ->orderBy('ROOM_NUMBER', 'ASC')
        ->execute()->fetchAll();

    }

    return $this->render('KulaHEdSchedulingBundle:CoreRooms:index.html.twig', array('rooms' => $rooms));

  }

  public function chooserAction() {
    $this->authorize();
    $data = $this->chooser('HEd.Room')->createChooserMenu($this->request->query->get('q'));
    return $this->JSONResponse($data);
  }

}

Fix eager loading of orgterm.

Fix eager loading of orgterm.


<?php

namespace Stratify\ErrorHandlerModule;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;

class ErrorHandlerMiddleware
{
    private $whoops;

    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response,
        callable $next
    ) : ResponseInterface
    {
        try {
            return $next($request, $response);
        } catch (\Exception $e) {
            if (! $this->whoops) {
                $this->whoops = new Run();
                $this->whoops->writeToOutput(false);
                $this->whoops->allowQuit(false);
                $this->whoops->pushHandler(new PrettyPageHandler);
            }

            $output = $this->whoops->handleException($e);

            $response->getBody()->write($output);
            return $response;
        }
    }
}

<?php

namespace Stratify\ErrorHandlerModule;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;

class ErrorHandlerMiddleware
{
    private $whoops;

    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response,
        callable $next
    ) : ResponseInterface
    {
        try {
            return $next($request, $response);
        } catch (\Exception $e) {
            if (! $this->whoops) {
                $this->whoops = new Run();
                $this->whoops->writeToOutput(false);
                $this->whoops->allowQuit(false);
                $this->whoops->pushHandler(new PrettyPageHandler);
            }

            $output = $this->whoops->handleException($e);

            $response->getBody()->write($output);

            return $response->withStatus(500);
        }
    }
}

Set status 500 on error

Set status 500 on error


<?php

namespace Tests;

use PHPUnit_Framework_TestCase;
use Laravel\Tinker\TinkerCaster;
use Illuminate\Support\Collection;

class TinkerCasterTest extends PHPUnit_Framework_TestCase
{
    public function testCanCastCollection()
    {
        $caster = new TinkerCaster;

        $result = $caster->castCollection(new Collection(['foo', 'bar']));

        $this->assertSame([['foo', 'bar']], array_values($result));
    }
}

<?php

namespace Tests;

use PHPUnit\Framework\TestCase;
use Laravel\Tinker\TinkerCaster;
use Illuminate\Support\Collection;

class TinkerCasterTest extends TestCase
{
    public function testCanCastCollection()
    {
        $caster = new TinkerCaster;

        $result = $caster->castCollection(new Collection(['foo', 'bar']));

        $this->assertSame([['foo', 'bar']], array_values($result));
    }
}

Use PSR-1 in PHPunit TestCase

Use PSR-1 in PHPunit TestCase


<?php

namespace Retrinko\CottonTail\Message;

use PhpAmqpLib\Message\AMQPMessage;
use Retrinko\CottonTail\Message\Messages\BasicMessage;
use Retrinko\CottonTail\Message\Messages\RpcRequestMessage;
use Retrinko\CottonTail\Message\Messages\RpcResponseMessage;

class MessageFactory
{
    /**
     * @param AMQPMessage $amqpMessage
     *
     * @return BasicMessage|RpcRequestMessage|RpcResponseMessage
     *
     */
    public static function byAMQPMessage(AMQPMessage $amqpMessage)
    {
        try
        {
            $msgType = $amqpMessage->get(BasicMessage::PROPERTY_TYPE);
        }
        catch (\Exception $e)
        {
            // No type defined in AMQPMessage properties. Load BasicMessage.
            $msgType = '';
        }

        switch ($msgType)
        {
            case BasicMessage::TYPE_RPC_RESPONSE:
                $message = RpcResponseMessage::loadAMQPMessage($amqpMessage);
                break;
            case BasicMessage::TYPE_RPC_REQUEST:
                $message = RpcRequestMessage::loadAMQPMessage($amqpMessage);
                break;
            case BasicMessage::TYPE_PLAIN_TEXT:
            default:
                $message = BasicMessage::loadAMQPMessage($amqpMessage);
                break;
        }

        return $message;
    }
}

<?php

namespace Retrinko\CottonTail\Message;

use PhpAmqpLib\Message\AMQPMessage;
use Retrinko\CottonTail\Message\Messages\BasicMessage;
use Retrinko\CottonTail\Message\Messages\RpcRequestMessage;
use Retrinko\CottonTail\Message\Messages\RpcResponseMessage;

class MessageFactory
{
    /**
     * @param AMQPMessage $amqpMessage
     *
     * @return BasicMessage|RpcRequestMessage|RpcResponseMessage
     *
     */
    public static function byAMQPMessage(AMQPMessage $amqpMessage)
    {
        try
        {
            $msgType = $amqpMessage->get(MessageInterface::PROPERTY_TYPE);
        }
        catch (\Exception $e)
        {
            // No type defined in AMQPMessage properties. Load BasicMessage.
            $msgType = '';
        }

        switch ($msgType)
        {
            case MessageInterface::TYPE_RPC_RESPONSE:
                $message = RpcResponseMessage::loadAMQPMessage($amqpMessage);
                break;
            case MessageInterface::TYPE_RPC_REQUEST:
                $message = RpcRequestMessage::loadAMQPMessage($amqpMessage);
                break;
            case MessageInterface::TYPE_BASIC:
            default:
                $message = BasicMessage::loadAMQPMessage($amqpMessage);
                break;
        }

        return $message;
    }
}

Use MessageInterface for reading constants.


<?php
/**
* @package     jelix
* @subpackage  jsoap module
* @author      Laurent Jouanneau
* @contributor
* @copyright   2009-2015 Laurent Jouanneau
* @link        http://www.jelix.org
* @licence     GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
*/

class jsoapModuleInstaller extends jInstallerModule {

    function install() {

        // configure the entry point
        $entrypoint = $this->getParameter('entrypoint');

        if (!$entrypoint) {
            $entrypoint = 'soap';
        }
        if (!file_exists(jApp::wwwPath($entrypoint.'.php'))) {
            $this->copyFile('files/soap.php', jApp::wwwPath($entrypoint.'.php'));
        }

        // setup the configuration
        if (!file_exists(jApp::configPath($entrypoint.'/config.ini.php'))) {
            $this->copyFile('files/config.ini.php', jApp::configPath($entrypoint.'/config.ini.php'));
        }

        if ($this->entryPoint->getMainConfigIni()->getValue('soap', 'responses') === null) {
            $this->entryPoint->getMainConfigIni()->setValue('soap', "jsoap~jResponseSoap", "responses");
        }

        $this->declareNewEntryPoint($entrypoint, 'soap', $entrypoint.'/config.ini.php');
    }
}

<?php
/**
* @package     jelix
* @subpackage  jsoap module
* @author      Laurent Jouanneau
* @contributor
* @copyright   2009-2015 Laurent Jouanneau
* @link        http://www.jelix.org
* @licence     GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
*/

class jsoapModuleInstaller extends jInstallerModule {

    function install() {

        // configure the entry point
        $entrypoint = $this->getParameter('entrypoint');

        if (!$entrypoint) {
            $entrypoint = 'soap';
        }
        if (!file_exists(jApp::wwwPath($entrypoint.'.php'))) {
            $this->copyFile('files/soap.php', jApp::wwwPath($entrypoint.'.php'));
        }

        // setup the configuration
        if (!file_exists(jApp::appConfigPath($entrypoint.'/config.ini.php'))) {
            $this->copyFile('files/config.ini.php', jApp::appConfigPath($entrypoint.'/config.ini.php'));
        }

        if ($this->entryPoint->getMainConfigIni()->getValue('soap', 'responses') === null) {
            $this->entryPoint->getMainConfigIni()->setValue('soap', "jsoap~jResponseSoap", "responses");
        }

        $this->declareNewEntryPoint($entrypoint, 'soap', $entrypoint.'/config.ini.php');
    }
}

Copy entrypoint config to new app/config/


<?php

namespace RIPS\Connector\Exceptions;

use RIPS\Connector\Entities\Response;

class HttpException extends \RuntimeException
{
    /** @var Response */
    private $response;

    /**
     * @param Response $response
     * @throws \Exception if no proper error is found
     */
    public function __construct(Response $response)
    {
        $this->response = $response;
        $data = $response->getDecodedData();

        if (!is_object($data)) {
            throw new \Exception('Unexpected response in exception: ' . $data);
        }

        parent::__construct(
            property_exists($data, 'message') ? $data->message : '',
            property_exists($data, 'code') ? $data->code : 0
        );
    }

    /**
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }
}

<?php

namespace RIPS\Connector\Exceptions;

use RIPS\Connector\Entities\Response;

class HttpException extends \RuntimeException
{
    /** @var Response */
    private $response;

    /**
     * @param Response $response
     * @throws \Exception if no proper error is found
     */
    public function __construct(Response $response)
    {
        $this->response = $response;
        $data = $response->getDecodedData();

        if (!is_object($data)) {
            throw new \Exception('Unexpected response in exception: ' . $response->getRawData());
        }

        parent::__construct(
            property_exists($data, 'message') ? $data->message : '',
            property_exists($data, 'code') ? $data->code : 0
        );
    }

    /**
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }
}

Return raw output in unexpected exception


<?php

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

class CreateModifiersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('amazo_mods', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('parent_id')->unsigned()->default('1')->required();
            $table->integer('damage_type_id')->unsigned()->default('1')->required();
            $table->decimal('amount',14,4)->default('1')->required();
            $table->enum('mod_type', ['*', '+'])->default('*');

            $table->foreign('parent_id')->references('id')->on('damage_types')->onDelete('cascade');
            $table->foreign('damage_type_id')->references('id')->on('damage_types')->onDelete('cascade');

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('amazo_mods');
    }
}

<?php

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

class CreateModifiersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('amazo_mods', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('parent_id')->unsigned()->default('1')->required();
            $table->integer('damage_type_id')->unsigned()->default('1')->required();
            $table->decimal('amount',14,4)->default('1')->required();
            $table->boolean('cumulative')->default('0')->required();
            $table->enum('mod_type', ['*', '+'])->default('*');

            $table->foreign('parent_id')->references('id')->on('damage_types')->onDelete('cascade');
            $table->foreign('damage_type_id')->references('id')->on('damage_types')->onDelete('cascade');

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('amazo_mods');
    }
}

Adjust migration for cumulative field.

Adjust migration for cumulative field.


<?php

namespace Omnipay\GoPay\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;

class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        $redirectUrl = $this->getRedirectUrl();
        return is_string($redirectUrl);
    }

    /**
     * Gets the redirect target url.
     */
    public function getRedirectUrl()
    {
        if (!is_array($this->data) || !isset($this->data['gw_url']) || !is_string($this->data['gw_url'])) {
            return null;
        }
        return $this->data['gw_url'];
    }

    /**
     * Get the required redirect method (either GET or POST).
     */
    public function getRedirectMethod()
    {
        return 'GET';
    }

    /**
     * Gets the redirect form data array, if the redirect method is POST.
     */
    public function getRedirectData()
    {
        return null;
    }

    /**
     * @return string
     */
    public function getState()
    {
        return $this->data['state'];
    }

    public function getTransactionReference()
    {
        if (isset($this->data['id'])) {
            return $this->data['id'];
        }
        return null;
    }

    public function getTransactionId()
    {
        if (isset($this->data['order_number'])) {
            return $this->data['order_number'];
        }
        return null;
    }

}

<?php

namespace Omnipay\GoPay\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RedirectResponseInterface;

class PurchaseResponse extends AbstractResponse implements RedirectResponseInterface
{
    /**
     * Is the response successful?
     *
     * @return boolean
     */
    public function isSuccessful()
    {
        $redirectUrl = $this->getRedirectUrl();
        return is_string($redirectUrl);
    }

    /**
     * Gets the redirect target url.
     */
    public function getRedirectUrl()
    {
        if (!is_array($this->data) || !isset($this->data['gw_url']) || !is_string($this->data['gw_url'])) {
            return null;
        }
        return $this->data['gw_url'];
    }

    /**
     * Get the required redirect method (either GET or POST).
     */
    public function getRedirectMethod()
    {
        return 'GET';
    }

    /**
     * Gets the redirect form data array, if the redirect method is POST.
     */
    public function getRedirectData()
    {
        return null;
    }

    public function getCode()
    {
        if (isset($this->data['state'])) {
            return $this->data['state'];
        }
        return null;
    }

    public function getTransactionReference()
    {
        if (isset($this->data['id'])) {
            return $this->data['id'];
        }
        return null;
    }

    public function getTransactionId()
    {
        if (isset($this->data['order_number'])) {
            return $this->data['order_number'];
        }
        return null;
    }

}

Use native method to get status code from response


<?php

declare(strict_types=1);

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\AdminBundle\Model;

final class Revision
{
    /**
     * @var int|string
     */
    private $id;

    /**
     * @var \DateTime
     */
    private $timestamp;

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

    /**
     * @param int|string $id
     */
    public function __construct($id, \DateTime $timestamp, string $username)
    {
        $this->id = $id;
        $this->timestamp = $timestamp;
        $this->username = $username;
    }

    /**
     * @return int|string
     */
    public function getRev()
    {
        return $this->id;
    }

    public function getTimestamp(): \DateTime
    {
        return $this->timestamp;
    }

    public function getUsername(): string
    {
        return $this->username;
    }
}

<?php

declare(strict_types=1);

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\AdminBundle\Model;

final class Revision
{
    /**
     * @var int|string
     */
    private $id;

    /**
     * @var \DateTimeInterface
     */
    private $dateTime;

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

    /**
     * @param int|string $id
     */
    public function __construct($id, \DateTimeInterface $dateTime, string $username)
    {
        $this->id = $id;
        $this->dateTime = $dateTime;
        $this->username = $username;
    }

    /**
     * @return int|string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return int|string
     */
    public function getRev()
    {
        return $this->id;
    }

    public function getDateTime(): \DateTimeInterface
    {
        return $this->dateTime;
    }

    public function getTimestamp(): \DateTimeInterface
    {
        return $this->dateTime;
    }

    public function getUsername(): string
    {
        return $this->username;
    }
}

Use DateTimeInterface and provide better getters


<?php

namespace Halfpastfour\PHPChartJS\Options;

use Halfpastfour\PHPChartJS\ArraySerializableInterface;
use Halfpastfour\PHPChartJS\Delegate\ArraySerializable;
use Halfpastfour\PHPChartJS\Options\Layout\Padding;
use Zend\Json\Json;

/**
 * Class Layout
 * @package Halfpastfour\PHPChartJS\Options
 */
class Layout implements ArraySerializableInterface, \JsonSerializable
{
    use ArraySerializable;

    /**
     * @var int|Padding
     */
    private $padding;

    /**
     * @param int $padding
     */
    public function setPadding($padding)
    {
        $this->padding = intval($padding);
    }

    /**
     * @return int
     */
    public function getPadding()
    {
        return $this->padding;
    }

    /**
     * @return Padding
     */
    public function padding()
    {
        if (is_null($this->padding)) {
            $this->padding  = new Padding();
        }

        return $this->padding;
    }

    /**
     * @return string
     */
    public function jsonSerialize()
    {
        return Json::encode($this->getArrayCopy());
    }
}

<?php

namespace Halfpastfour\PHPChartJS\Options;

use Halfpastfour\PHPChartJS\ArraySerializableInterface;
use Halfpastfour\PHPChartJS\Delegate\ArraySerializable;
use Halfpastfour\PHPChartJS\Options\Layout\Padding;
use Zend\Json\Json;

/**
 * Class Layout
 *
 * @package Halfpastfour\PHPChartJS\Options
 */
class Layout implements ArraySerializableInterface, \JsonSerializable
{
    use ArraySerializable;

    /**
     * @var int|Padding
     */
    private $padding;

    /**
     * @param int $padding
     */
    public function setPadding($padding)
    {
        $this->padding = intval($padding);
    }

    /**
     * @return int|Padding
     */
    public function getPadding()
    {
        return $this->padding;
    }

    /**
     * @return Padding
     */
    public function padding()
    {
        if (is_null($this->padding)) {
            $this->padding = new Padding();
        }

        return $this->padding;
    }

    /**
     * @return string
     * @throws \ReflectionException
     * @throws \Zend_Reflection_Exception
     */
    public function jsonSerialize()
    {
        return Json::encode($this->getArrayCopy());
    }
}

Fix PHPDoc return type and CS

Fix PHPDoc return type and CS


<?php

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

class CreateRoleUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on(config('trusty.model.user'))->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }

}

<?php

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

class CreateRoleUserTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on(config('auth.table'))->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }

}

Fix wrong table preferrence for role_user


<?php
/**
 * This file is part of the CalendArt package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace CalendArt\Adapter\Office365;

use GuzzleHttp\Client as Guzzle;

use CalendArt\AbstractCalendar,
    CalendArt\Adapter\AdapterInterface;

/**
 * Office365 Adapter - He knows how to dialog with office 365's calendars !
 *
 * This requires to have an OAuth2 token established with the following scopes :
 * - Calendar.read
 * - Calendar.write
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class Office365Adapter implements AdapterInterface
{
    /** @param string $token access token delivered by azure's oauth system */
    public function __construct($token)
    {
        $this->guzzle = new Guzzle(['base_url' => 'https://outlook.office365.com/api/v1.0/me/',
                                    'defaults' => ['exceptions' => false,
                                                    'headers' => ['Authorization' => sprintf('Bearer %s', $token),
                                                                  'Content-Type' => 'application/json',
                                                                  'Accept' => 'application/json;odata=verbose']]]);
    }

    /** {@inheritDoc} */
    public function getCalendarApi()
    {
    }

    /** {@inheritDoc} */
    public function getEventApi()
    {
    }
}

<?php
/**
 * This file is part of the CalendArt package
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 *
 * @copyright Wisembly
 * @license   http://www.opensource.org/licenses/MIT-License MIT License
 */

namespace CalendArt\Adapter\Office365;

use GuzzleHttp\Client as Guzzle;

use CalendArt\AbstractCalendar,
    CalendArt\Adapter\AdapterInterface;

/**
 * Office365 Adapter - He knows how to dialog with office 365's calendars !
 *
 * This requires to have an OAuth2 token established with the following scopes :
 * - Calendar.read
 * - Calendar.write
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class Office365Adapter implements AdapterInterface
{
    /** @param string $token access token delivered by azure's oauth system */
    public function __construct($token)
    {
        $this->guzzle = new Guzzle(['base_url' => 'https://outlook.office365.com/api/v1.0/me/',
                                    'defaults' => ['exceptions' => false,
                                                    'headers' => ['Authorization' => sprintf('Bearer %s', $token),
                                                                  'Content-Type' => 'application/json',
                                                                  'Accept' => 'application/json']]]);
    }

    /** {@inheritDoc} */
    public function getCalendarApi()
    {
    }

    /** {@inheritDoc} */
    public function getEventApi()
    {
    }
}

Remove odata part in the accept - Office365 is not happy


{{ $input['label'] }}

	@if ($value)
		{{ HTML::image($file_url.'/'.$name.'/'.$value, '', ['class' => 'uploaded_image']) }}
	@endif

	{{ Form::file($name, ['class' => 'form-control']) }}

		Изображение будет {{ trans('image.method.'.$input['image'][0]['method']) }}
		под {{ join('x', $input['image'][0]['size']) }}

{{ $input['label'] }}

	@if ($value)
		{{ HTML::image($file_url.'/'.$name.'/'.$value, '', ['class' => 'uploaded_image']) }}
	@endif

	{{ Form::file($name, ['class' => 'form-control']) }}

		Изображение будет {{ trans('image.method.'.$input['image'][0]['method']) }}
		@if (isset($input['image'][0]['size']))
		    под {{ join('x', $input['image'][0]['size']) }}
        	@endif

Fix input image for form builder

Fix input image for form builder