<?php

use Illuminate\Database\Seeder;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i=0; $i<5; $i++) {

            $firstName = $faker->firstName;
            $lastName = $faker->lastName;

            $newUser = App\User::create(
                [
                    'name_first'    => $firstName,
                    'name_last'     => $lastName,
                    "affiliation_id"=> $faker->numberBetween(1,57),
                    "email"         => $faker->email,
                    'password'      => 'admin',
                    'nomination_limit'=> 5
                ]
            );

            $this->command->info("Seeded user {$firstName} {$lastName}");

            $role_id = $faker->numberBetween(1, 5);
            $role = \App\Role::find($role_id);

            $newUser->attachRole($role);

        }

        // Add dev account until we enable registration
        $newUser = App\User::create(
            [
                'name_first'    => "Developer",
                'name_last'     => "lastName",
                "affiliation_id"=> 1,
                "email"         => "developer@codeforcharlotte.org",
                'password'      => 'admin'
            ]
        );

        $role = \App\Role::find(1);
        $newUser->attachRole($role);

    }
}

<?php

use Illuminate\Database\Seeder;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i=0; $i<5; $i++) {

            $firstName = $faker->firstName;
            $lastName = $faker->lastName;

            $newUser = App\User::create(
                [
                    'name_first'    => $firstName,
                    'name_last'     => $lastName,
                    "affiliation_id"=> $faker->numberBetween(1,57),
                    "email"         => $faker->email,
                    'password'      => 'admin',
                    'nomination_limit'=> 5
                ]
            );

            $this->command->info("Seeded user {$firstName} {$lastName}");

            $role_id = $faker->numberBetween(1, 5);
            $role = \App\Role::find($role_id);

            $newUser->attachRole($role);

        }

        // Add dev account until we enable registration
        $newUser = App\User::create(
            [
                'name_first'        => "Developer",
                'name_last'         => "lastName",
                "affiliation_id"    => 1,
                "email"             => "developer@codeforcharlotte.org",
                'password'          => 'admin',
                'nomination_limit'  => 5
            ]
        );

        $role = \App\Role::find(1);
        $newUser->attachRole($role);

    }
}

Set nomination limit for dev user in seeder


<?php
if((empty($int_security)) OR ($int_security!=$game_se_code)){
	header("Location: ../../index.php?error=16");
	exit();
}
$newversion="0.8.1";
foreach($game_server as $chiave=>$elemento){
if($chiave!=999){
$db->Setdb($chiave);
$check=$db->QuerySelect("SELECT version FROM config WHERE id=".$chiave);
if($check['version']!=$newversion AND $newversion==$game_version){

$db->QueryMod("");

$db->QueryMod("UPDATE `config` SET version='".$newversion."' WHERE id=".$chiave);
echo sprintf($lang['aggiornato_db_server'],$chiave,$newversion)."
";
}/*se non aggiornato*/else{
echo sprintf($lang['non_aggiornato_db_server'],$chiave)."
";
}
}//se non  quello di sviluppo principale
}//fine per ogni server
?>

<?php
if((empty($int_security)) OR ($int_security!=$game_se_code)){
	header("Location: ../../index.php?error=16");
	exit();
}
$oldversion="0.8.0";
$newversion="0.8.1";
foreach($game_server as $chiave=>$elemento){
    $db->Setdb($chiave);
    $check=$db->QuerySelect("SELECT version FROM config WHERE id=".$chiave);
    if($check['version']==$oldversion AND $newversion==$game_version){

    $db->QueryMod("");

    $db->QueryMod("UPDATE `config` SET version='".$newversion."' WHERE id=".$chiave);
    echo sprintf($lang['aggiornato_db_server'],$chiave,$newversion)."
";
    }else{
        echo sprintf($lang['non_aggiornato_db_server'],$chiave)."
";
    }
    }//end for each server
?>

Improve the game database update to new version

- add old version check for not do incompatible update
- converted to utf8 and added indentation


<?php

namespace Omnipay\Mollie\Message;

/**
 * Mollie Abstract Request
 */
abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest
{
    protected $endpoint = 'https://secure.mollie.nl/xml/ideal';

    public function getPartnerId()
    {
        return $this->getParameter('partnerId');
    }

    public function setPartnerId($value)
    {
        return $this->setParameter('partnerId', $value);
    }

    public function getIssuer()
    {
        return $this->getParameter('issuer');
    }

    public function setIssuer($value)
    {
        return $this->setParameter('issuer', $value);
    }

    protected function getBaseData()
    {
        $data = array();

        if ($this->getTestMode()) {
            $data['testmode'] = 'true';
        }

        return $data;
    }

    public function send()
    {
        $httpResponse = $this->httpClient->post($this->endpoint, null, $this->getData())->send();

        return $this->response = new Response($this, $httpResponse->xml());
    }
}

<?php

namespace Omnipay\Mollie\Message;

/**
 * Mollie Abstract Request
 */
abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest
{
    protected $endpoint = 'https://secure.mollie.nl/xml/ideal';

    public function getPartnerId()
    {
        return $this->getParameter('partnerId');
    }

    public function setPartnerId($value)
    {
        return $this->setParameter('partnerId', $value);
    }

    public function getIssuer()
    {
        return $this->getParameter('issuer');
    }

    public function setIssuer($value)
    {
        return $this->setParameter('issuer', $value);
    }

    protected function getBaseData()
    {
        $data = array();

        if ($this->getTestMode()) {
            $data['testmode'] = 'true';
        }

        return $data;
    }

    public function sendData($data)
    {
        $httpResponse = $this->httpClient->post($this->endpoint, null, $data)->send();

        return $this->response = new Response($this, $httpResponse->xml());
    }
}

Update gateways to use new sendData method


<?php

/*
 * This file is part of the Secret Santa project.
 *
 * (c) JoliCode <coucou@jolicode.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace JoliCode\SecretSanta\Slack;

use JoliCode\Slack\Api\Client;
use JoliCode\Slack\ClientFactory as DefaultClientFactory;

class ClientFactory
{
    /** @var array<string, Client> */
    private $clientsByToken = [];

    public function getClientForToken(string $token): Client
    {
        if (!isset($this->clientsByToken[$token])) {
            $this->clientsByToken[$token] = DefaultClientFactory::create($token);
        }

        return $this->clientsByToken[$token];
    }
}

<?php

/*
 * This file is part of the Secret Santa project.
 *
 * (c) JoliCode <coucou@jolicode.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace JoliCode\SecretSanta\Slack;

use JoliCode\Slack\Api\Client;
use JoliCode\Slack\ClientFactory as DefaultClientFactory;
use Psr\Http\Client\ClientInterface as PsrHttpClient;

class ClientFactory
{
    private PsrHttpClient $httpClient;

    /** @var array<string, Client> */
    private $clientsByToken = [];

    public function __construct(PsrHttpClient $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    public function getClientForToken(string $token): Client
    {
        if (!isset($this->clientsByToken[$token])) {
            $this->clientsByToken[$token] = DefaultClientFactory::create($token, $this->httpClient);
        }

        return $this->clientsByToken[$token];
    }
}

Use default Symfony HTTP client with profiler enabled


<?php
namespace Concrete\Core\Application\Service;
use Concrete\Core\Page\Type\Type;
use PageType;
use \Concrete\Core\Http\ResponseAssetGroup;
use \Concrete\Core\Page\Type\Composer\Control as PageTypeComposerControl;
use Loader;
class Composer {

	public function display(Type $pagetype, $page = false) {
        $pagetype->renderComposerOutputForm($page);
	}

	public function displayButtons(PageType $pagetype, $page = false) {
		Loader::element('page_types/composer/form/output/buttons', array(
			'pagetype' => $pagetype,
			'page' => $page
		));
	}

	public function addAssetsToRequest(PageType $pt, Controller $cnt) {
		$list = PageTypeComposerControl::getList($pt);
		foreach($list as $l) {
			$l->addAssetsToRequest($cnt);
		}
	}

}

<?php
namespace Concrete\Core\Application\Service;
use Concrete\Core\Page\Type\Type;
use PageType;
use \Concrete\Core\Http\ResponseAssetGroup;
use \Concrete\Core\Page\Type\Composer\Control\Control as PageTypeComposerControl;
use Loader;
class Composer {

	/**
	 * @param Type $pagetype
	 * @param bool|\Page $page
	 */
	public function display(Type $pagetype, $page = false) {
        $pagetype->renderComposerOutputForm($page);
	}

	/**
	 * @param PageType $pagetype
	 * @param bool|\Page $page
	 */
	public function displayButtons(PageType $pagetype, $page = false) {
		Loader::element('page_types/composer/form/output/buttons', array(
			'pagetype' => $pagetype,
			'page' => $page
		));
	}

	/**
	 * @param PageType $pt
	 * @param \Controller $cnt
	 */
	public function addAssetsToRequest(PageType $pt, \Controller $cnt) {
		$list = PageTypeComposerControl::getList($pt);
		foreach($list as $l) {
			$l->addAssetsToRequest($cnt);
		}
	}

}

Fix composer helper and comment it

Fix composer helper and comment it


<?php

namespace OpenOrchestra\ModelInterface\Model;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * Interface ContentTypeInterface
 */
interface ContentTypeInterface extends FieldTypeContainerInterface, StatusableInterface, TranslatedValueContainerInterface, BlameableInterface, TimestampableInterface
{
    /**
     * @param string $contentTypeId
     */
    public function setContentTypeId($contentTypeId);

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

    /**
     * @param boolean $deleted
     */
    public function setDeleted($deleted);

    /**
     * @return boolean
     */
    public function getDeleted();

    /**
     * @param FieldTypeInterface $fields
     */
    public function setFields(FieldTypeInterface $fields);

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

    /**
     * @param TranslatedValueInterface $name
     */
    public function addName(TranslatedValueInterface $name);

    /**
     * @param TranslatedValueInterface $name
     */
    public function removeName(TranslatedValueInterface $name);

    /**
     * @param string $language
     *
     * @return string
     */
    public function getName($language = 'en');

    /**
     * @return ArrayCollection
     */
    public function getNames();

    /**
     * @param int $version
     */
    public function setVersion($version);

    /**
     * @return int
     */
    public function getVersion();
}

<?php

namespace OpenOrchestra\ModelInterface\Model;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * Interface ContentTypeInterface
 */
interface ContentTypeInterface extends FieldTypeContainerInterface, StatusableInterface, TranslatedValueContainerInterface, BlameableInterface, TimestampableInterface
{
    /**
     * @param string $contentTypeId
     */
    public function setContentTypeId($contentTypeId);

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

    /**
     * @param boolean $deleted
     */
    public function setDeleted($deleted);

    /**
     * @return boolean
     */
    public function getDeleted();

    /**
     * @param string $template
     */
    public function setTemplate($template);

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

    /**
     * @param FieldTypeInterface $fields
     */
    public function setFields(FieldTypeInterface $fields);

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

    /**
     * @param TranslatedValueInterface $name
     */
    public function addName(TranslatedValueInterface $name);

    /**
     * @param TranslatedValueInterface $name
     */
    public function removeName(TranslatedValueInterface $name);

    /**
     * @param string $language
     *
     * @return string
     */
    public function getName($language = 'en');

    /**
     * @return ArrayCollection
     */
    public function getNames();

    /**
     * @param int $version
     */
    public function setVersion($version);

    /**
     * @return int
     */
    public function getVersion();
}

Add edit form custom template for content


<?php

namespace CodeTool\ArtifactDownloader\Scope\Config\Factory;

use CodeTool\ArtifactDownloader\DomainObject\DomainObjectInterface;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfig;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigChildNode;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigInterface;

class ScopeConfigFactory implements ScopeConfigFactoryInterface
{
    /**
     * @param DomainObjectInterface $do
     *
     * @return ScopeConfigChildNode
     */
    private function createChildNode(DomainObjectInterface $do)
    {
        return new ScopeConfigChildNode($do->toArray());
    }

    /**
     * @param string                 $scopeName
     * @param DomainObjectInterface $do
     *
     * @return ScopeConfigInterface
     */
    public function createFromDo($scopeName, DomainObjectInterface $do)
    {
        $scopeRules = [];
        foreach ($do->get('rules') as $rule) {
            $scopeRules[] = $this->createChildNode($rule);
        }

        return new ScopeConfig($scopeName, $do->get('exact_match'), $scopeRules);
    }
}

<?php

namespace CodeTool\ArtifactDownloader\Scope\Config\Factory;

use CodeTool\ArtifactDownloader\DomainObject\DomainObjectInterface;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfig;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigChildNode;
use CodeTool\ArtifactDownloader\Scope\Config\ScopeConfigInterface;

class ScopeConfigFactory implements ScopeConfigFactoryInterface
{
    /**
     * @param DomainObjectInterface $do
     *
     * @return ScopeConfigChildNode
     */
    private function createChildNode(DomainObjectInterface $do)
    {
        return new ScopeConfigChildNode($do->toArray());
    }

    /**
     * @param string                 $scopeName
     * @param DomainObjectInterface $do
     *
     * @return ScopeConfigInterface
     */
    public function createFromDo($scopeName, DomainObjectInterface $do)
    {
        $scopeRules = [];
        foreach ($do->get('rules') as $rule) {
            $scopeRules[] = $this->createChildNode($rule);
        }

        return new ScopeConfig($scopeName, $do->getOrDefault('exact_match', false), $scopeRules);
    }
}

Make exact_match non-required option (false by default)


<?php

use AspectMock\Test as test;
class PHPServerTest extends \Codeception\TestCase\Test
{
    use \Robo\Task\Development\loadTasks;
    /**
     * @var \AspectMock\Proxy\ClassProxy
     */
    protected $process;

    protected function _before()
    {
        $this->process = test::double('Symfony\Component\Process\Process', [
            'run' => false,
            'start' => false,
            'getOutput' => 'Hello world',
            'getExitCode' => 0
        ]);
        test::double('Robo\Task\Development\PhpServer', ['getOutput' => new \Symfony\Component\Console\Output\NullOutput()]);
    }

    public function testServerBackgroundRun()
    {
        $this->taskServer('8000')->background()->run();
        $this->process->verifyInvoked('start');
    }

    public function testServerRun()
    {
        $this->taskServer('8000')->run();
        $this->process->verifyInvoked('run');
    }

    public function testServerCommand()
    {
        verify(
            $this->taskServer('8000')
                ->dir('web')
                ->getCommand()
        )->equals('php -S 127.0.0.1:8000 -t web');
    }

}

<?php

use AspectMock\Test as test;
class PHPServerTest extends \Codeception\TestCase\Test
{
    use \Robo\Task\Development\loadTasks;
    /**
     * @var \AspectMock\Proxy\ClassProxy
     */
    protected $process;

    protected function _before()
    {
        $this->process = test::double('Symfony\Component\Process\Process', [
            'run' => false,
            'start' => false,
            'getOutput' => 'Hello world',
            'getExitCode' => 0
        ]);
        test::double('Robo\Task\Development\PhpServer', ['getOutput' => new \Symfony\Component\Console\Output\NullOutput()]);
    }

    public function testServerBackgroundRun()
    {
        $this->taskServer('8000')->background()->run();
        $this->process->verifyInvoked('start');
    }

    public function testServerRun()
    {
        $this->taskServer('8000')->run();
        $this->process->verifyInvoked('run');
    }

    public function testServerCommand()
    {
        verify(
            $this->taskServer('8000')
                ->dir('web')
                ->getCommand()
        )->equals('exec php -S 127.0.0.1:8000 -t web');
    }

}

Adjust PhpServer unit test (add "exec")

Adjust PhpServer unit test (add "exec")


<?php
$config = dirname(__FILE__) . '/../app/config/main.php';
require(__DIR__ . '/../vendor/autoload.php');

// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 10);

Yii::createWebApplication($config)->run();

<?php
$config = dirname(__FILE__) . '/../app/config/main.php';
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii/framework/yii.php');

// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 10);

Yii::createWebApplication($config)->run();

Add yii require to index.php

Add yii require to index.php


<?php

namespace UWDOEM\Framework\Filter;

class SearchFilter extends Filter {

    /**
     * @param \UWDOEM\Framework\Row\RowInterface[] $rows
     */
    protected function setOptionsByRows(array $rows) {
        if (sizeof($rows) >= 1) {
            $this->_options = $rows[0]->getFieldBearer()->getFieldNames();
        }
    }
}

<?php

namespace UWDOEM\Framework\Filter;

use UWDOEM\Framework\Filter\FilterControls;
use UWDOEM\Framework\FilterStatement\ExcludingFilterStatement;

class SearchFilter extends Filter {

    /**
     * @param $handle
     * @param \UWDOEM\Framework\FilterStatement\FilterStatementInterface[] $statements
     * @param FilterInterface|null $nextFilter
     */
    public function __construct($handle, array $statements, FilterInterface $nextFilter = null) {

        for($i=0;$i<=5;$i++) {
            $fieldname = FilterControls::getControl($handle, "fieldname$i");
            $operation = FilterControls::getControl($handle, "operation$i");
            $value = FilterControls::getControl($handle, "value$i");

            if ($fieldname && $operation && $value) {
                $statements[] = new ExcludingFilterStatement($fieldname, $operation, $value, null);
            }

        }

        $this->_feedback = "";
        foreach ($statements as $statement) {
            $fieldname = $statement->getFieldName();
            $value = $statement->getCriterion();
            $operation = $statement->getCondition();

            $this->_feedback .= $this->_feedback ? ", " : "";
            $this->_feedback .= $fieldname . " " . $operation . " " . $value;
        }
        parent::__construct($handle, $statements, $nextFilter);
    }

    /**
     * @param \UWDOEM\Framework\Row\RowInterface[] $rows
     */
    protected function setOptionsByRows(array $rows) {
        if (sizeof($rows) >= 1) {
            $this->_options = $rows[0]->getFieldBearer()->getFieldNames();
        }
    }
}

Add feedback to search filter.

Add feedback to search filter.


<?php

namespace Vision\Hydrator\Strategy;

use Vision\Annotation\Property;
use Vision\Annotation\WebEntity;
use Zend\Hydrator\Strategy\StrategyInterface;

class WebEntitiesStrategy implements StrategyInterface
{
    /**
     * @param WebEntity[] $value
     * @return array
     */
    public function extract($value)
    {
        return array_map(function(WebEntity $webEntity) {
            return array_filter([
                'entityId' => $webEntity->getEntityId(),
                'score' => $webEntity->getScore(),
                'description' => $webEntity->getDescription(),
            ]);
        }, $value);
    }

    /**
     * @param array $value
     * @return WebEntity[]
     */
    public function hydrate($value)
    {
        $webEntities = [];

        foreach ($value as $webEntityInfo) {
            $webEntities[] = new WebEntity($webEntityInfo['entityId'], $webEntityInfo['description'], isset($webEntityInfo['score']) ? $webEntityInfo['score'] : null);
        }

        return $webEntities;
    }
}

<?php

namespace Vision\Hydrator\Strategy;

use Vision\Annotation\Property;
use Vision\Annotation\WebEntity;
use Zend\Hydrator\Strategy\StrategyInterface;

class WebEntitiesStrategy implements StrategyInterface
{
    /**
     * @param WebEntity[] $value
     * @return array
     */
    public function extract($value)
    {
        return array_map(function(WebEntity $webEntity) {
            return array_filter([
                'entityId' => $webEntity->getEntityId(),
                'score' => $webEntity->getScore(),
                'description' => $webEntity->getDescription(),
            ]);
        }, $value);
    }

    /**
     * @param array $value
     * @return WebEntity[]
     */
    public function hydrate($value)
    {
        $webEntities = [];

        foreach ($value as $webEntityInfo) {
            $webEntities[] = new WebEntity(
                $webEntityInfo['entityId'],
                isset($webEntityInfo['description']) ? $webEntityInfo['description'] : null,
                isset($webEntityInfo['score']) ? $webEntityInfo['score'] : null
            );
        }

        return $webEntities;
    }
}

Allow description to be null

Allow description to be null


<?php
function renderAuth0Form($canShowLegacyLogin = true)
{
    if(is_user_logged_in())
        return;

    $wordpress_login_enabled = $canShowLegacyLogin && (WP_Auth0_Options::get('wordpress_login_enabled') == 1);

    if (!$wordpress_login_enabled || !isset($_GET['wle'])) {
        include ('auth0-login-form.php');
    }else{
        add_action('login_footer', array(WP_Auth0::class, 'render_back_to_auth0'));
    }
}

?>

<?php
function renderAuth0Form($canShowLegacyLogin = true)
{
    if(is_user_logged_in())
        return;

    $wordpress_login_enabled = $canShowLegacyLogin && (WP_Auth0_Options::get('wordpress_login_enabled') == 1);

    if (!$wordpress_login_enabled || !isset($_GET['wle'])) {
        require_once ('auth0-login-form.php');
    }else{
        add_action('login_footer', array(WP_Auth0::class, 'render_back_to_auth0'));
    }
}

?>

Fix to allow to show multiple times the auth0 login form in the same page


<?php

namespace Sofa\Revisionable\Laravel;

use Illuminate\Console\Command;
use Illuminate\Support\Composer;
use Illuminate\Filesystem\Filesystem;

class RevisionsUpgradeCommand extends Command
{
    /** @var string */
    protected $name = 'revisions:upgrade-5.3';

    /** @var string */
    protected $description = 'Create a migration upgrading to v5.3';

    /** @var \Illuminate\Filesystem\Filesystem */
    protected $files;

    /** @var \Illuminate\Foundation\Composer */
    protected $composer;

    /**
     * @param \Illuminate\Filesystem\Filesystem $files
     * @param \Illuminate\Foundation\Composer   $composer
     */
    public function __construct(Filesystem $files, Composer $composer)
    {
        parent::__construct();
        $this->files = $files;
        $this->composer = $composer;
    }

    /**
     * Execute the console command.
     */
    public function fire()
    {
        $path = $this->createBaseMigration();
        $this->files->put($path, $this->files->get(__DIR__.'/../migrations/upgrade-5.3stub'));
        $this->info('Revisions upgrade migration created successfully!');
        $this->composer->dumpAutoloads();
    }

    /**
     * Create a base migration file for the table.
     *
     * @return string
     */
    protected function createBaseMigration()
    {
        $name = 'add_morph_relation_to_revisions';

        $path = $this->laravel->databasePath().'/migrations';

        return $this->laravel['migration.creator']->create($name, $path);
    }
}

<?php

namespace Sofa\Revisionable\Laravel;

use Illuminate\Console\Command;
use Illuminate\Support\Composer;
use Illuminate\Filesystem\Filesystem;

class RevisionsUpgradeCommand extends Command
{
    /** @var string */
    protected $name = 'revisions:upgrade-5.3';

    /** @var string */
    protected $description = 'Create a migration upgrading to v5.3';

    /** @var \Illuminate\Filesystem\Filesystem */
    protected $files;

    /** @var \Illuminate\Foundation\Composer */
    protected $composer;

    /**
     * @param \Illuminate\Filesystem\Filesystem $files
     * @param \Illuminate\Foundation\Composer   $composer
     */
    public function __construct(Filesystem $files, Composer $composer)
    {
        parent::__construct();
        $this->files = $files;
        $this->composer = $composer;
    }

    /**
     * Execute the console command.
     */
    public function fire()
    {
        $path = $this->createBaseMigration();
        $this->files->put($path, $this->files->get(__DIR__.'/../migrations/upgrade-5.3.stub'));
        $this->info('Revisions upgrade migration created successfully!');
        $this->composer->dumpAutoloads();
    }

    /**
     * Create a base migration file for the table.
     *
     * @return string
     */
    protected function createBaseMigration()
    {
        $name = 'add_morph_relation_to_revisions';

        $path = $this->laravel->databasePath().'/migrations';

        return $this->laravel['migration.creator']->create($name, $path);
    }
}

Fix typo in RevisionUpgrade command.

Fix typo in RevisionUpgrade command.


<?php

declare(strict_types=1);

namespace NewTwitchApi\Resources;

use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;

class TeamsApi extends AbstractResource
{
    /**
     * @throws GuzzleException
     * @link https://dev.twitch.tv/docs/api/reference#get-channel-teams
     */
    public function getChannelTeams(string $bearer, string $broadcasterId): ResponseInterface
    {
        $queryParamsMap = [];

        $queryParamsMap[] = ['key' => 'broadcaster_id', 'value' => $broadcasterId];

        return $this->getApi('teams/channel', $bearer, $queryParamsMap);
    }

    /**
     * @throws GuzzleException
     * @link https://dev.twitch.tv/docs/api/reference#get-teams
     */
    public function getTeams(string $bearer, string $name = null, string $id = null): ResponseInterface
    {
        $queryParamsMap = [];

        if ($name) {
            $queryParamsMap[] = ['key' => 'name', 'value' => $name];
        }

        if ($id) {
            $queryParamsMap[] = ['key' => 'id', 'value' => $id];
        }

        return $this->getApi('teams', $bearer, $queryParamsMap);
    }
}

<?php

declare(strict_types=1);

namespace NewTwitchApi\Resources;

use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;

class TeamsApi extends AbstractResource
{
    /**
     * @throws GuzzleException
     * @link https://dev.twitch.tv/docs/api/reference#get-channel-teams
     */
    public function getChannelTeams(string $bearer, string $broadcasterId): ResponseInterface
    {
        $queryParamsMap = [];

        $queryParamsMap[] = ['key' => 'broadcaster_id', 'value' => $broadcasterId];

        return $this->getApi('teams/channel', $bearer, $queryParamsMap);
    }

    /**
     * @throws GuzzleException
     */
    public function getTeamsByName(string $bearer, string $name): ResponseInterface
    {
        return $this->getTeams($bearer, $name, null);
    }

    /**
     * @throws GuzzleException
     */
    public function getTeamsById(string $bearer, string $id): ResponseInterface
    {
        return $this->getTeams($bearer, null, $id);
    }

    /**
     * @throws GuzzleException
     * @link https://dev.twitch.tv/docs/api/reference#get-teams
     */
    public function getTeams(string $bearer, string $name = null, string $id = null): ResponseInterface
    {
        $queryParamsMap = [];

        if ($name) {
            $queryParamsMap[] = ['key' => 'name', 'value' => $name];
        }

        if ($id) {
            $queryParamsMap[] = ['key' => 'id', 'value' => $id];
        }

        return $this->getApi('teams', $bearer, $queryParamsMap);
    }
}

Add getTeamByName / getTeamById helpers

Add getTeamByName / getTeamById helpers


<?php namespace Krucas\Notification;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('edvinaskrucas/notification');
        $this->app['events']->fire('notification.booted', $this->app['notification']);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');

        $this->app['notification'] = $this->app->share(function ($app) {
            $config = $app['config'];

            $notification = new Notification(
                $config->get('notification::default_container'),
                $config->get('notification::default_types'),
                $config->get('notification::default_format'),
                $config->get('notification::default_formats')
            );

            $notification->setEventDispatcher($this->app['events']);

            return $notification;
        });

        $this->app->bind('Krucas\Notification\Subscriber', function ($app) {
            return new Subscriber($app['session.store'], $app['config']);
        });

        $this->app['events']->subscribe('Krucas\Notification\Subscriber');
    }

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

<?php namespace Krucas\Notification;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('edvinaskrucas/notification');
        $this->app['events']->fire('notification.booted', $this->app['notification']);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config');

        $this->app['notification'] = $this->app->share(function ($app) {
            $config = $app['config'];

            $notification = new Notification(
                $config->get('notification::default_container'),
                $config->get('notification::default_types'),
                $config->get('notification::default_format'),
                $config->get('notification::default_formats')
            );

            $notification->setEventDispatcher($app['events']);

            return $notification;
        });

        $this->app->bind('Krucas\Notification\Subscriber', function ($app) {
            return new Subscriber($app['session.store'], $app['config']);
        });

        $this->app['events']->subscribe('Krucas\Notification\Subscriber');
    }

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

Fix $this usage when in Closure

Fix $this usage when in Closure


<?php

namespace Omnipay\AuthorizeNet\Message;

/**
 * Authorize.Net AIM Purchase Request
 */
class AIMPurchaseRequest extends AIMAuthorizeRequest
{
    protected $action = 'AUTH_CAPTURE';

    public function getData()
    {
        $this->validate('amount', 'card');
        $this->getCard()->validate();

        $data = $this->getBaseData();
        $data['x_customer_ip'] = $this->getClientIp();
        $data['x_card_num'] = $this->getCard()->getNumber();
        $data['x_exp_date'] = $this->getCard()->getExpiryDate('my');
        $data['x_card_code'] = $this->getCard()->getCvv();

        if ($this->getTestMode()) {
            $data['x_test_request'] = 'TRUE';
        }

        return array_merge($data, $this->getBillingData());
    }
}

<?php

namespace Omnipay\AuthorizeNet\Message;

/**
 * Authorize.Net AIM Purchase Request
 */
class AIMPurchaseRequest extends AIMAuthorizeRequest
{
    protected $action = 'AUTH_CAPTURE';
}

Use identical parent getData() function

Use identical parent getData() function


<?php
namespace PureBilling\Bundle\SDKBundle\Store\Base;

use Symfony\Component\Validator\Constraints as Assert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
use PureMachine\Bundle\SDKBundle\Store\Base\SymfonyBaseStore;

abstract class Element extends SymfonyBaseStore
{
    public function __construct($data=null)
    {
        parent::__construct($data);
        //Set Short type of class
        // PureMachine\Bundle\SDKBundle\Store\Billing\CC become Billing\CC
        $this->type = str_replace('PureBilling\Bundle\SDKBundle\Store\\', '',
                                  get_class($this));
    }

    /**
     * @Store\Property(description="type of the current answer")
     * @Assert\Type("string")
     * @Assert\NotBlank
     */
    protected $type;

    public function getClassName()
    {
        $class = explode('\\', get_called_class());

        return end($class);
    }
}

<?php
namespace PureBilling\Bundle\SDKBundle\Store\Base;

use Symfony\Component\Validator\Constraints as Assert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
use PureMachine\Bundle\SDKBundle\Store\Base\SymfonyBaseStore;

abstract class Element extends SymfonyBaseStore
{
    public function __construct($data=null)
    {
        parent::__construct($data);
        //Set Short type of class
        // PureMachine\Bundle\SDKBundle\Store\Billing\CC become Billing\CC
        $this->type = str_replace('PureBilling\Bundle\SDKBundle\Store\\', '',
                                  get_class($this));
    }

    /**
     * @Store\Property(description="type of the current answer")
     * @Assert\Type("string")
     * @Assert\NotBlank
     */
    protected $type;
}

Fix className bug: should not be shorten


<?php
return [
    // we are only going to care about metrics dimensions with have these whitelisted dimensions
    'Dimensions' => [
        "InstanceId" => true,
    ],
    'Statistics' => [
        'CPUUtilization' => ['Maximum'],
        'StatusCheckFailed' => ['Sum'],
    ],
    'Unit' => [
        'CPUUtilization' => 'Percent',
        'StatusCheckFailed' => 'Count'
    ],
    'AWS/EC2' => [
        // metrics to pull for every machine
        "__global" => [
            'CPUUtilization' => true,
        ],
        // a per machine metric, you can use nice machine names instanceid will be looked up
        'web100.pagelydev.com' => [
            'StatusCheckFailed' => true
        ],
    ]
];

<?php
return [
    // we are only going to care about metrics dimensions with have these whitelisted dimensions
    'Dimensions' => [
        "InstanceId" => true,
    ],
    // Possible Values  SampleCount | Average | Sum | Minimum | Maximum
    'Statistics' => [
        'CPUUtilization' => ['Maximum'],
        'StatusCheckFailed' => ['Sum'],
        'DiskWriteOps' => ['Average'],
        'DiskReadOps' => ['Average'],
        'NetworkIn' => ['Average'],
        'NetworkOut' => ['Average'],
        'DiskReadBytes' => ['Average'],
        'DiskWriteBytes' => ['Average'],
    ],
    // Possible Values Seconds | Microseconds | Milliseconds | Bytes | Kilobytes | Megabytes | Gigabytes | Terabytes | Bits | Kilobits | Megabits | Gigabits | Terabits | Percent | Count | Bytes/Second | Kilobytes/Second | Megabytes/Second | Gigabytes/Second | Terabytes/Second | Bits/Second | Kilobits/Second | Megabits/Second | Gigabits/Second | Terabits/Second | Count/Second | None
    'Unit' => [
        'CPUUtilization' => 'Percent',
        'StatusCheckFailed' => 'Count',
        'DiskWriteOps' => 'Count',
        'DiskReadOps' => 'Count',
        'NetworkIn' => 'Bytes',
        'NetworkOut' => 'Bytes',
        'DiskReadBytes' => 'Bytes',
        'DiskWriteBytes' => 'Bytes',
    ],
    'AWS/EC2' => [
        // metrics to pull for every machine
        "__global" => [
            'CPUUtilization' => true,
            'DiskReadOps' => true,
            'DiskWriteOps' => true,
            'DiskReadBytes' => true,
            'DiskWriteBytes' => true,
            'NetworkIn' => true,
            'NetworkOut' => true,
        ],
        // a per machine metric, you can use nice machine names instanceid will be looked up
        'web100.pagelydev.com' => [
            'StatusCheckFailed' => true
        ],
    ]
];

Make things more useful (NetworkIn/Out still seems weird


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
// use Jenssegers\Mongodb\Schema\Blueprint;

class CreateLabelsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('labels', function(Blueprint $table) {

			//$collection->unique(array('vocabulary', 'identifier'));

			$table->increments('id');
			$table->integer('concept_id')->unsigned();
			$table->enum('class', array('prefLabel', 'altLabel', 'hiddenLabel'));
			$table->string('lang');
			$table->string('value');
			$table->unique(array('concept_id', 'lang', 'value'));
			$table->timestamps();

			$table->foreign('concept_id')
				->references('id')->on('concepts')
				->onDelete('cascade');

		});

		DB::unprepared('
			ALTER TABLE `labels`
			DEFAULT CHARACTER SET utf8
			COLLATE utf8_bin
		');

	}

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

}

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
// use Jenssegers\Mongodb\Schema\Blueprint;

class CreateLabelsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('labels', function(Blueprint $table) {

			//$collection->unique(array('vocabulary', 'identifier'));

			$table->increments('id');
			$table->integer('concept_id')->unsigned();
			$table->enum('class', array('prefLabel', 'altLabel', 'hiddenLabel'));
			$table->string('lang');
			$table->string('value');
			$table->unique(array('concept_id', 'class', 'lang', 'value'));
			$table->timestamps();

			$table->foreign('concept_id')
				->references('id')->on('concepts')
				->onDelete('cascade');

		});

		DB::unprepared('
			ALTER TABLE `labels`
			DEFAULT CHARACTER SET utf8
			COLLATE utf8_bin
		');

	}

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

}

Reduce uniqueness constraint on labels table

In the WebDewey data we have cases where prefLabel = altLabel


<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 20/10/2016
 * Time: 23:36
 */

namespace vr\api\doc\components;

use yii\base\BaseObject;
use yii\helpers\ArrayHelper;

/**
 * Class DocCommentParser
 * @package vr\api\doc\components
 * @property string $description
 */
class DocCommentParser extends BaseObject
{
    /**
     * @var
     */
    public $source;

    /**
     * @var
     */
    public $params;

    /**
     *
     */
    public function init()
    {
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return trim(ArrayHelper::getValue(explode(PHP_EOL, $this->source), 1), " *");
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 20/10/2016
 * Time: 23:36
 */

namespace vr\api\doc\components;

use yii\base\BaseObject;

/**
 * Class DocCommentParser
 * @package vr\api\doc\components
 * @property string $description
 */
class DocCommentParser extends BaseObject
{
    /**
     * @var
     */
    public $source;

    /**
     * @var
     */
    public $params;

    /**
     *
     */
    public function init()
    {
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        $string = explode(PHP_EOL, $this->source);
        $values = array_splice($string, 1);

        array_walk($values, function (&$item) {
            $item = trim($item, '* /\t\r\n');
        });

        return implode(array_filter($values), '<br/>');
    }
}

Change the way of parsing method comments to make the app starting displaying proper comments


#!/usr/bin/php -q
<?php
require_once('../lib/YleApi.php');

if (file_exists("config.ini"))
	$config=parse_ini_file("config.ini", true);
else
	die("Configuration file config.ini is missing\n");

if ($argc!==2)
	die("Channel ID required!\n");

$pid=$argv[1];
$api=$config['Generic'];

$c=new YleApiClient($api['app_id'], $api['app_key'], $api['decrypt']);
$c->set_debug(true);

$a=$c->programs_nowplaying($pid);
file_put_contents('nowplaying.json', json_encode($a, JSON_PRETTY_PRINT));
print_r($a);
?>

#!/usr/bin/php -q
<?php
require_once('../lib/YleApi.php');

if (file_exists("config.ini"))
	$config=parse_ini_file("config.ini", true);
else
	die("Configuration file config.ini is missing\n");

if ($argc!==2)
	die("Channel ID required!\n");

$pid=$argv[1];
$api=$config['Generic'];

$c=new YleApiClient($api['app_id'], $api['app_key'], $api['decrypt']);
$c->set_debug(true);

$a=$c->programs_nowplaying($pid);
file_put_contents('nowplaying.json', json_encode($a, JSON_PRETTY_PRINT));

$np=YleNowplaying::create($a);
//print_r($a);
?>

Add test of YleNowplaying object

Add test of YleNowplaying object


<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\Metadata;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class AnnotationReader implements Reader
{
    /**
     * @psalm-param class-string $className
     */
    public function forClass(string $className): MetadataCollection
    {
        return MetadataCollection::fromArray([]);
    }

    /**
     * @psalm-param class-string $className
     */
    public function forMethod(string $className, string $methodName): MetadataCollection
    {
        return MetadataCollection::fromArray([]);
    }
}

<?php declare(strict_types=1);
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace PHPUnit\Util\Metadata;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class AnnotationReader implements Reader
{
    /**
     * @psalm-param class-string $className
     */
    public function forClass(string $className): MetadataCollection
    {
        $result = [];

        return MetadataCollection::fromArray($result);
    }

    /**
     * @psalm-param class-string $className
     */
    public function forMethod(string $className, string $methodName): MetadataCollection
    {
        $result = [];

        return MetadataCollection::fromArray($result);
    }
}

Make this slightly less as simple as possible


<?php get_header();?>

<?php $catid = get_cat_id( single_cat_title("",false) );?>

<title>Search result for <?php   echo '"' . $_GET['s'] . '"' . ' - '; bloginfo('name'); ?></title>

	<?php get_search_form();?>

	<?php if (have_posts()) : while(have_posts()) : the_post();?>

			<a href="<?php the_permalink();?>" title = "<?php the_title();?>">
<?php the_title();?>

Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?>

			<?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?>

<?php the_excerpt(); ?>

		<?php endwhile; else : ?>

<?php _e('No post right now.'); ?>

		<?php endif; ?>

<?php get_footer();?>

<?php get_header();?>

<?php $catid = get_cat_id( single_cat_title("",false) );?>

<title>Search result for <?php   echo '"' . $_GET['s'] . '"' . ' - '; bloginfo('name'); ?></title>

	<?php get_search_form();?>

	<?php if (have_posts()) : while(have_posts()) : the_post();?>

			<a href="<?php the_permalink();?>" title = "<?php the_title();?>">
<?php the_title();?>

Posted by <?php the_author();?> on <?php the_time('F jS, Y'); ?>

			<?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumbnail'));} ?>

<?php the_excerpt(); ?>

		<?php endwhile; else : ?>

We can't found what you are looking for.

Try other keyword or <a href="<?php echo get_option('home');?>">Go Home?

		<?php endif; ?>

Remove footer to avoid floating footer

Remove footer to avoid floating footer


<?php
namespace SmoothPhp\CommandBus;

use Ramsey\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;

/**
 * Class Command
 * @package SmoothPhp\CommandBus
 * @author Simon Bennett <simon.bennett@smoothphp.com>
 */
abstract class BaseCommand implements Command
{
    /**
     * @var string
     */
    private $commandId;

    /**
     * @return string
     */
    public function __toString()
    {
        return get_class($this) . ':' . $this->getCommandId();
    }

    /**
     * @return string
     */
    public function getCommandId()
    {
        return $this->commandId ?: $this->commandId = (string) Uuid::uuid4();
    }
}

Fix some style issues from scrutinizer

[CS] Fix some style issues from scrutinizer


<?php
/**
 * This class should represent the whole text
 *
 * @author newloki
 */
namespace \Language\Text;
use \Language\Languages\LanguagesAbstract;

class Text
{
    /** @var string $_text */
    protected $_text;

    /** @var \Language\Languages\LanguagesAbstract $_language */
    protected $_language;

    /**
     * Create an text object based on text as string and his corresponding
     * language
     *
     * @param  $_text
     * @param \Language\Languages\LanguagesAbstract $_language
     */
    public function __construct($_text, LanguagesAbstract $_language)
    {
        $this->_text = (string) $_text;
        $this->_language = $_language;
    }

}

<?php
/**
 * This class should represent the whole text
 *
 * @author newloki
 */
namespace \Language\Text;
use \Language\Languages\LanguagesAbstract
    \Language\Word;

class Text
{
    /** @var string $_text */
    protected $_text;

    /** @var \Language\Languages\LanguagesAbstract $_language */
    protected $_language;

    /** @var array $_words */
    protected $_words = array();

    /**
     * Create an text object based on text as string and his corresponding
     * language
     *
     * @param  $_text
     * @param \Language\Languages\LanguagesAbstract $_language
     */
    public function __construct($_text, LanguagesAbstract $_language)
    {
        $this->_text = (string) $_text;
        $this->_language = $_language;
    }

    /**
     * Get an array of words for this text, if there are no words present,
     * this method call method to generate words from text
     *
     * @return array of \Language\Word\Word
     */
    public function getWords()
    {
        if(empty($this->_words)) {
            $this->_splitText();
        }

        return $this->_words;
    }

    /**
     * Set an word for this text, and give him a language (this give the
     * ability to use foreign words in text)
     *
     * @param  $_word
     * @param LanguagesAbstract|null $_language
     * @return void
     */
    public function setWord($_word, LanguagesAbstract $_language = null)
    {
        if (empty($_language)) {
            $_language = $this->_language;
        }

        $this->_words[$_word] = new Word($_word, $_language);
    }

    /**
     * Split this text into words and create a word object for each of them,
     * if there is nothing stored, else increase counter for this word
     *
     * @return void
     */
    protected function _splitText()
    {
        $words = str_word_count($this->_text, 1);
        foreach ($words as $word) {
            if (!array_key_exists($word, $this->_words)) {
                $this->_words[$word] = new Word($word, $this->_language);
            } else {
                /** @var $_word Word */
                $_word = $this->_words[$word];
                $_word->increaseCounter();
            }
        }
    }
}

Add methods to split text into words

Add methods to split text into words


<?php
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer\Initializer\Template;

/**
 * Generate a Laravel deployer configuration.
 *
 * @author Anton Medvedev <anton@medv.io>
 */
class LaravelTemplate extends FrameworkTemplate
{
    protected function getRecipe()
    {
        return 'laravel';
    }
}

<?php
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer\Initializer\Template;

/**
 * Generate a Laravel deployer configuration.
 *
 * @author Anton Medvedev <anton@medv.io>
 */
class LaravelTemplate extends FrameworkTemplate
{
    protected function getRecipe()
    {
        return 'laravel';
    }

    protected function getExtraContent()
    {
        return <<<PHP

// Migrate database before symlink new release.

before('deploy:symlink', 'artisan:migrate');

PHP;

    }
}

Add db migrate to laravel template

Add db migrate to laravel template


<?php

namespace Oro\Bundle\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="oro_user_api")
 * @ORM\Entity
 */
class UserApi
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var User
     *
     * @ORM\OneToOne(targetEntity="User", inversedBy="api", fetch="LAZY")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     */
    protected $user;

    /**
     * @var string
     *
     * @ORM\Column(name="api_key", type="string", unique=true, length=255, nullable=false)
     */
    protected $apiKey;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set apiKey
     *
     * @param string $apiKey
     *
     * @return UserApi
     */
    public function setApiKey($apiKey)
    {
        $this->apiKey = $apiKey;

        return $this;
    }

    /**
     * Get apiKey
     *
     * @return string
     */
    public function getApiKey()
    {
        return $this->apiKey;
    }

    /**
     * Set user
     *
     * @param User $user
     *
     * @return UserApi
     */
    public function setUser(User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Generate random API key
     *
     * @return string
     */
    public function generateKey()
    {
        return bin2hex(hash('sha1', uniqid(mt_rand(), true), true));
    }
}

<?php

namespace Oro\Bundle\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="oro_session")
 * @ORM\Entity
 */
class Session
{
    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=255)
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="sess_data", type="text", nullable=false)
     */
    protected $value;

    /**
     * @var int
     *
     * @ORM\Column(name="sess_time", type="integer", nullable=false)
     */
    protected $time;
}

BAP-1365: Develop WAMP server application for broadcasting client data updates (PHP side)
- session entity added


<?php

namespace Forex\Bundle\EmailBundle\Command;

use Forex\Bundle\EmailBundle\Entity\EmailMessage;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;

class SendPendingEmailsCommand extends ContainerAwareCommand
{
    protected $em;
    protected $sender;

    protected function configure()
    {
        $this
            ->setName('email:send-pending-emails')
            ->setDescription('Sends all pending emails')
        ;
    }

    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();
        $request = new Request();
        $container->set('request', $request);
        $container->enterScope('request');

        $this->em = $container->get('doctrine.orm.default_entity_manager');
        $this->sender = $container->get('forex.email_sender');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $progress = $this->getHelperSet()->get('progress');

        $pendingMessages = $this->em->getRepository('ForexEmailBundle:EmailMessage')->findPendingEmails();

        $progress->start($output, count($pendingMessages));

        foreach ($pendingMessages as $message) {
            $this->sender->send($message);
            $progress->advance();
        }

        $progress->finish();
        $this->em->flush();
    }
}

<?php

namespace Forex\Bundle\EmailBundle\Command;

use Forex\Bundle\EmailBundle\Entity\EmailMessage;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;

class SendPendingEmailsCommand extends ContainerAwareCommand
{
    protected $em;
    protected $sender;

    protected function configure()
    {
        $this
            ->setName('email:send-pending-emails')
            ->setDescription('Sends all pending emails')
        ;
    }

    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $container = $this->getContainer();
        $request = new Request();
        $request->headers->set('host', $container->getParameter('cli_host'));
        $container->set('request', $request);
        $container->enterScope('request');

        $this->em = $container->get('doctrine.orm.default_entity_manager');
        $this->sender = $container->get('forex.email_sender');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $progress = $this->getHelperSet()->get('progress');

        $pendingMessages = $this->em->getRepository('ForexEmailBundle:EmailMessage')->findPendingEmails();

        $progress->start($output, count($pendingMessages));

        foreach ($pendingMessages as $message) {
            $this->sender->send($message);
            $progress->advance();
        }

        $progress->finish();
        $this->em->flush();
    }
}

Set the host for the cli command

Set the host for the cli command


<?php

class Denkmal_Model_TagTest extends CMTest_TestCase {

    protected function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testCreate() {
        $tag = Denkmal_Model_Tag::create('foo');
        $this->assertInstanceOf('Denkmal_Model_Tag', $tag);
        $this->assertSame('foo', $tag->getLabel());
        $this->assertSame(true, $tag->getActive());
    }

    public function testGetSetLabel() {
        $tag = Denkmal_Model_Tag::create('foo');
        $tag->setLabel('bar');
        $this->assertSame('bar', $tag->getLabel());
        $tag->setLabel('foo');
        $this->assertSame('foo', $tag->getLabel());
    }

    public function testGetSetActive() {
        $tag = Denkmal_Model_Tag::create('foo');
        $tag->setActive(false);
        $this->assertSame(false, $tag->getActive());
        $tag->setActive(true);
        $this->assertSame(true, $tag->getActive());
    }

    /**
     * @expectedException CM_Exception_Invalid
     */
    public function testDelete() {
        $tag = Denkmal_Model_Tag::create('foo');
        $tag->delete();
    }
}

<?php

class Denkmal_Model_TagTest extends CMTest_TestCase {

    protected function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testCreate() {
        $tag = Denkmal_Model_Tag::create('foo');
        $this->assertInstanceOf('Denkmal_Model_Tag', $tag);
        $this->assertSame('foo', $tag->getLabel());
        $this->assertSame(true, $tag->getActive());
    }

    /**
     * @expectedException CM_Db_Exception
     */
    public function testCreateDuplicate() {
        Denkmal_Model_Tag::create('foo');
        Denkmal_Model_Tag::create('foo');
    }

    public function testGetSetLabel() {
        $tag = Denkmal_Model_Tag::create('foo');
        $tag->setLabel('bar');
        $this->assertSame('bar', $tag->getLabel());
        $tag->setLabel('foo');
        $this->assertSame('foo', $tag->getLabel());
    }

    public function testGetSetActive() {
        $tag = Denkmal_Model_Tag::create('foo');
        $tag->setActive(false);
        $this->assertSame(false, $tag->getActive());
        $tag->setActive(true);
        $this->assertSame(true, $tag->getActive());
    }

    /**
     * @expectedException CM_Exception_Invalid
     */
    public function testDelete() {
        $tag = Denkmal_Model_Tag::create('foo');
        $tag->delete();
    }
}

Add test for duplicate tags creation

Add test for duplicate tags creation


<?php

declare(strict_types=1);

namespace App\Mail;

use App\Models\DocuSignEnvelope;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Symfony\Component\Mime\Email;

class MembershipAgreementDocuSignEnvelopeReceived extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    public DocuSignEnvelope $envelope;

    /**
     * Create a new message instance.
     */
    public function __construct(DocuSignEnvelope $envelope)
    {
        $this->envelope = $envelope;
    }

    /**
     * Build the message.
     */
    public function build(): self
    {
        return $this->from('noreply@my.robojackets.org', 'RoboJackets')
                    ->to($this->envelope->signedBy->gt_email, $this->envelope->signedBy->name)
                    ->cc('Membership Agreement Archives <'.config('services.membership_agreement_archive_email').'>')
                    ->subject('Membership agreement signed')
                    ->text('mail.agreement.docusignenvelopereceived')
                    ->withSymfonyMessage(static function (Email $email): void {
                        $email->replyTo('RoboJackets <hello@robojackets.org>');
                    })
                    ->tag('agreement-docusign-received')
                    ->metadata('envelope-id', strval($this->envelope->id));
    }
}

<?php

declare(strict_types=1);

namespace App\Mail;

use App\Models\DocuSignEnvelope;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Symfony\Component\Mime\Email;

class MembershipAgreementDocuSignEnvelopeReceived extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    public DocuSignEnvelope $envelope;

    /**
     * Create a new message instance.
     */
    public function __construct(DocuSignEnvelope $envelope)
    {
        $this->envelope = $envelope;
    }

    /**
     * Build the message.
     */
    public function build(): self
    {
        return $this->from('noreply@my.robojackets.org', 'RoboJackets')
                    ->to($this->envelope->signedBy->gt_email, $this->envelope->signedBy->name)
                    ->cc('Membership Agreement Archives', config('services.membership_agreement_archive_email'))
                    ->subject('Membership agreement signed')
                    ->text('mail.agreement.docusignenvelopereceived')
                    ->withSymfonyMessage(static function (Email $email): void {
                        $email->replyTo('RoboJackets <hello@robojackets.org>');
                    })
                    ->tag('agreement-docusign-received')
                    ->metadata('envelope-id', strval($this->envelope->id));
    }
}

Fix CC field on acknowledgement email

Fix CC field on acknowledgement email


<?php

use Diskus\Model\Topic;

class Diskus_Create_Topics {

	/**
	 * Make changes to the database.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('diskus_topics', function ($table)
		{
			$table->increments('id');
			$table->integer('user_id')->unsigned();
			$table->string('title')->nullable();
			$table->text('content')->nullable();
			$table->string('status')->default(Topic::STATUS_PUBLISH);
			$table->timestamps();
		});
	}

	/**
	 * Revert the changes to the database.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('diskus_topics');
	}

}

<?php

use Diskus\Model\Topic;

class Diskus_Create_Topics {

	/**
	 * Make changes to the database.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('diskus_topics', function ($table)
		{
			$table->increments('id');

			$table->integer('user_id')->unsigned();
			$table->string('title')->nullable();
			$table->text('content')->nullable();
			$table->text('metadata')->nullable();
			$table->string('status')->default(Topic::STATUS_PUBLISH);

			$table->timestamps();

			$table->index('user_id');
			$table->index('status');
		});
	}

	/**
	 * Revert the changes to the database.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('diskus_topics');
	}

}

Update migration script for topics.

Update migration script for topics.

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


<?php

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

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class SecurityController extends AbstractController
{
    public function checkAction()
    {
        return new Response('OK');
    }

    public function profileAction()
    {
        return new Response('Welcome '.$this->getUser()->getUsername().'!');
    }
}

<?php

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

namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\AuthenticatorBundle;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class SecurityController extends AbstractController
{
    public function checkAction()
    {
        return new Response('OK');
    }

    public function profileAction()
    {
        return new Response('Welcome '.$this->getUser()->getUserIdentifier().'!');
    }
}

Fix call to deprecated getUsername() in tests


<?php

    class Database_operations {
        private $database;
        private $bird_db;

        // Class constructor
        function __construct($bird) {
            try {
                $this->bird_db = $bird;
                $this->database = new PDO(
                                'mysql:host=localhost;dbname=gonm;charset=utf8',
                                'root',
                                '');
            }
            catch(Exception $e) {
                die('Error : '.$e->getMessage());
            }
        }

        // Return an bird with all the informations
        function get_birds($code, $color) {
            $request = $this->database->prepare("SELECT * FROM " . $this->bird_db .
                                                " WHERE number = :number AND color = :color LIMIT 1");
            $request->execute(array(
                                "number" => $code,
                                "color" => $color)
                            );
            return $request;
        }

        function get_unique_colors_rings() {
            return $this->database->query("SELECT DISTINCT color FROM kentish_plover"); //. $this->bird_db . "");
        }
    }
?>

<?php

    class Database_operations {
        private $database;
        private $bird_db;

        // Class constructor
        function __construct($bird) {
            try {
                $this->bird_db = $bird;
                $this->database = new PDO(
                                'mysql:host=localhost;dbname=gonm;charset=utf8',
                                'root',
                                '');
            }
            catch(Exception $e) {
                die('Error : '.$e->getMessage());
            }
        }

        // Return an bird with all the informations
        function get_birds($code, $color) {
            $request = $this->database->prepare("SELECT * FROM " . $this->bird_db .
                                                " WHERE number = :number AND color = :color LIMIT 1");
            $request->execute(array(
                                "number" => $code,
                                "color" => $color)
                            );
            return $request;
        }

        // Get all the colors from the database
        function get_unique_colors_rings() {
            return $this->database->query("SELECT DISTINCT color FROM " . $this->bird_db);
        }
    }
?>

Update the function which return the unique colors


<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

require 'vendor/autoload.php';

$app = new Silex\Application();

$app->get('/', function() {
    return "Main application!";
});

$blog = new Silex\Application();

$blog->get('/', function() {
    return "This is the blog!";
});

$stack = (new Stack\Stack)
    ->push('Stack\UrlMap', array('/blog' => $blog));

$app = $stack->resolve($app);

$request = Request::createFromGlobals();
$response = $app->handle($request)->send();

$app->terminate($request, $response);

<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

require 'vendor/autoload.php';

$app = new Silex\Application();

$app->get('/', function() {
    return "Main application!";
});

$blog = new Silex\Application();

$blog->get('/', function() {
    return "This is the blog!";
});

$stack = (new Stack\Stack)
    ->push('Stack\UrlMap', ['/blog' => $blog]);

$app = $stack->resolve($app);

$request = Request::createFromGlobals();
$response = $app->handle($request)->send();

$app->terminate($request, $response);

Use short array syntax in array

Use short array syntax in array


<?php

use Fhaculty\Graph\Algorithm\Directed;

use Fhaculty\Graph\Graph;

use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne()
    {
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected, $graph);
    }

    public function testUndirected()
    {
        $n = 9;

        $loader = new CompleteGraph($n);
        $graph = $loader->createGraph();

        $this->assertEquals($n, $graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1)/2, $graph->getNumberOfEdges());
    }

    public function testDirected()
    {
        $n = 8;

        $loader = new CompleteGraph($n);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals($n, $graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1), $graph->getNumberOfEdges()); // n*(n-1) for directed graphs

        $alg = new Directed($graph);
        $this->assertTrue($alg->isDirected());

        $this->assertTrue($graph->isComplete());
    }
}

<?php

use Fhaculty\Graph\Algorithm\Complete;

use Fhaculty\Graph\Algorithm\Directed;

use Fhaculty\Graph\Graph;

use Fhaculty\Graph\Loader\CompleteGraph;

class CompleteGraphTest extends TestCase
{
    public function testOne()
    {
        $loader = new CompleteGraph(1);
        $graph = $loader->createGraph();

        $expected = new Graph();
        $expected->createVertex();

        $this->assertGraphEquals($expected, $graph);
    }

    public function testUndirected()
    {
        $n = 9;

        $loader = new CompleteGraph($n);
        $graph = $loader->createGraph();

        $this->assertEquals($n, $graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1)/2, $graph->getNumberOfEdges());
    }

    public function testDirected()
    {
        $n = 8;

        $loader = new CompleteGraph($n);
        $loader->setEnableDirectedEdges(true);
        $graph = $loader->createGraph();

        $this->assertEquals($n, $graph->getNumberOfVertices());
        $this->assertEquals($n*($n-1), $graph->getNumberOfEdges()); // n*(n-1) for directed graphs

        $alg = new Directed($graph);
        $this->assertTrue($alg->isDirected());

        $alg = new Complete($graph);
        $this->assertTrue($alg->isComplete());
    }
}

Add tests with 100% coverage for Algorithm\Complete


<?php
/**
 * BasicTest.php
 * Copyright (c) 2020 james@firefly-iii.org
 *
 * This file is part of Firefly III (https://github.com/firefly-iii).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

declare(strict_types=1);

namespace Tests\Feature;

use FireflyIII\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

/**
 * Class BasicTest
 */
class BasicTest extends TestCase
{
    use RefreshDatabase;
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest(): void
    {
        self::assertTrue(true);
    }

    /**
     *
     */
    public function testDatabase(): void
    {
        $this->assertDatabaseHas(
            'users', [
                       'email' => 'james@firefly',
                   ]
        );
    }
}

<?php
/**
 * BasicTest.php
 * Copyright (c) 2020 james@firefly-iii.org
 *
 * This file is part of Firefly III (https://github.com/firefly-iii).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

declare(strict_types=1);

namespace Tests\Feature;

use Tests\TestCase;

/**
 * Class BasicTest
 */
class BasicTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest(): void
    {
        self::assertTrue(true);
    }

    /**
     *
     */
    public function testDatabase(): void
    {
        $this->assertDatabaseHas(
            'users', [
                       'email' => 'james@firefly',
                   ]
        );
    }
}

Fix test with DB fixtures

Fix test with DB fixtures


<?php
// (c) Copyright 2002-2010 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$

// Wiki plugin to output ...
// - rlpowell

function wikiplugin_sub_help() {
        return tra("Displays text in subscript.").":
~np~{SUB()}text{SUB}~/np~";
}

function wikiplugin_sub_info() {
	return array(
		'name' => tra( 'Subscript' ),
		'documentation' => 'PluginSub',
		'description' => tra('Displays text in subscript.'),
		'prefs' => array( 'wikiplugin_sub' ),
		'body' => tra('text'),
		'icon' => 'pics/icons/text_subscript.png',
		'params' => array(
		),
	);
}

function wikiplugin_sub($data, $params)
{
        global $tikilib;

        extract ($params,EXTR_SKIP);
	return "$data";
}

<?php
// (c) Copyright 2002-2010 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$

// Wiki plugin to output ...
// - rlpowell

function wikiplugin_sub_help() {
        return tra("Displays text in subscript.").":
~np~{SUB()}text{SUB}~/np~";
}

function wikiplugin_sub_info() {
	return array(
		'name' => tra( 'Subscript' ),
		'documentation' => tra('PluginSub'),
		'description' => tra('Displays text in subscript.'),
		'prefs' => array( 'wikiplugin_sub' ),
		'body' => tra('text'),
		'icon' => 'pics/icons/text_subscript.png',
		'params' => array(
		),
	);
}

function wikiplugin_sub($data, $params)
{
        global $tikilib;

        extract ($params,EXTR_SKIP);
	return "$data";
}

Add tra to plugin info

Add tra to plugin info

git-svn-id: 9bac41f8ebc9458fc3e28d41abfab39641e8bd1c@31062 b456876b-0849-0410-b77d-98878d47e9d5


<?php

class CM_RenderAdapter_PageTest extends CMTest_TestCase {

    public function testFetchDescriptionKeywordsTitle() {
        $render = new CM_Frontend_Render();

        $page = $this->getMockBuilder('CM_Page_Abstract')->getMockForAbstractClass();
        /** @var CM_Page_Abstract $page */

        $renderAdapter = $this->getMockBuilder('CM_RenderAdapter_Page')
            ->setMethods(array('_fetchMetaTemplate'))
            ->setConstructorArgs(array($render, $page))
            ->getMock();
        $renderAdapter->expects($this->any())->method('_fetchMetaTemplate')->will($this->returnCallback(function ($tplName) {
            return 'test-' . $tplName . '.tpl';
        }));
        /** @var CM_RenderAdapter_Page $renderAdapter */

        $this->assertSame('test-meta-description.tpl', $renderAdapter->fetchDescription());
        $this->assertSame('test-meta-keywords.tpl', $renderAdapter->fetchKeywords());
        $this->assertSame('test-title.tpl', $renderAdapter->fetchTitle());
    }
}

<?php

class CM_RenderAdapter_PageTest extends CMTest_TestCase {

    public function testFetchDescriptionKeywordsTitleTrimming() {
        $render = new CM_Frontend_Render();

        $page = $this->getMockBuilder('CM_Page_Abstract')->getMockForAbstractClass();
        /** @var CM_Page_Abstract $page */

        $renderAdapter = $this->getMockBuilder('CM_RenderAdapter_Page')
            ->setMethods(array('_fetchTemplate'))
            ->setConstructorArgs(array($render, $page))
            ->getMock();
        $renderAdapter->expects($this->any())->method('_fetchTemplate')->will($this->returnCallback(function ($templateName) {
            return "\n \t test-" . $templateName . "\n";
        }));
        /** @var CM_RenderAdapter_Page $renderAdapter */

        $this->assertSame('test-meta-description', $renderAdapter->fetchDescription());
        $this->assertSame('test-meta-keywords', $renderAdapter->fetchKeywords());
        $this->assertSame('test-title', $renderAdapter->fetchTitle());
    }
}

Fix test for page renderadapter meta trimming


<?php

namespace Plummer\Calendar;

class Event
{
	protected $name;

	protected $dateStart;

	protected $dateEnd;

	protected $occurrenceDateStart;

	protected $calendar;

	protected $recurrenceType;

	protected function __construct($name, $dateStart, $dateEnd, &$calendar, $occurrenceDateStart = null)
	{
		$this->name = $name;
		$this->dateStart = $dateStart;
		$this->dateEnd = $dateEnd;
		$this->calendar = $calendar;
		$this->occurrenceDateStart = $occurrenceDateStart;
	}

	public static function make($name, $dateStart, $dateEnd, Calendar $calendar = null, $occurrenceDateStart = null)
	{
		return new static($name, $dateStart, $dateEnd, $calendar, $occurrenceDateStart);
	}

	public function setRecurrenceType(RecurrenceInterface $recurrenceType)
	{
		$this->recurrenceType = $recurrenceType;
	}

	public function setCalendar(Calendar $calendar)
	{
		$this->calendar = $calendar;
	}
}

<?php

namespace Plummer\Calendar;

class Event
{
	protected $uniqueId;

	protected $name;

	protected $dateStart;

	protected $dateEnd;

	protected $occurrenceDateStart;

	protected $calendar;

	protected $recurrenceType;

	protected function __construct($uniqueId, $name, $dateStart, $dateEnd, $occurrenceDateStart = null)
	{
		$this->uniqueId = $uniqueId;
		$this->name = $name;
		$this->dateStart = $dateStart;
		$this->dateEnd = $dateEnd;
		$this->occurrenceDateStart = $occurrenceDateStart;
	}

	public static function make($name, $dateStart, $dateEnd, $occurrenceDateStart = null)
	{
		return new static($name, $dateStart, $dateEnd, $occurrenceDateStart);
	}

	public function setRecurrenceType(RecurrenceInterface $recurrenceType)
	{
		$this->recurrenceType = $recurrenceType;
	}

	public function setCalendar(Calendar &$calendar)
	{
		$this->calendar = $calendar;
	}
}

Remove Calendar obligation on construction and add unique id.


<?php

class m111006_004445_create_language_table extends CDbMigration
{
	public function up()
	{
		$this->createTable('tbl_language', array(
			'id'       => 'pk',
			'language' => 'string NOT NULL UNIQUE'
		));
	}

	public function down()
	{
		$this->dropTable('tbl_language');
	}
}

<?php

class m111006_004445_create_language_table extends CDbMigration
{
	public function up()
	{
		$this->createTable('tbl_language', array(
			'id'       => 'pk',
			'language' => 'string NOT NULL UNIQUE'), 'engine = InnoDB');
	}

	public function down()
	{
		$this->dropTable('tbl_language');
	}
}

Create table with InnoDB engine

Create table with InnoDB engine


<?php

namespace Lily\Example\Application;

use Lily\Application\RoutedApplication;

use Lily\Example\Application\AdminApplication;

class FrontEndApplication extends RoutedApplication
{
    protected function routes()
    {
        return array(
            array('GET', '/', '<a href="/admin">admin'),
            array(NULL, '/admin(/**)', new AdminApplication),
        );
    }
}

<?php

namespace Lily\Example\Application;

use Lily\Application\RoutedApplication;

use Lily\Example\Application\AdminApplication;

class FrontEndApplication extends RoutedApplication
{
    protected function routes()
    {
        return array(
            array('GET', '/', '<a href="/admin">admin'),
            $this->adminApplicationRoute(),
        );
    }

    // Send all request methods and any URL beginning with `/admin` to Admin
    private function adminApplicationRoute()
    {
        return array(NULL, '/admin(/**)', new AdminApplication);
    }
}

Move admin application route to it's own documented method


<?php

namespace App\Transformers\Inbound\Collections;

use App\Transformers\Datum;
use App\Transformers\Inbound\CollectionsTransformer;

class Asset extends CollectionsTransformer
{

    protected function getIds(Datum $datum)
    {
        return  [
            'lake_guid' => $datum->id,
        ];
    }

    protected function getDates(Datum $datum)
    {
        $dates = parent::getDates($datum);

        return array_merge($dates, [
            'content_modified_at' => $datum->date('content_modified_at'),
        ]);
    }

    protected function getSync(Datum $datum, $test = false)
    {
        return [
            'imagedArtworks' => $this->getSyncAssetOf($datum, 'rep_of_artworks'),
            'imagedExhibitions' => $this->getSyncAssetOf($datum, 'rep_of_exhibitions'),
            'documentedArtworks' => $this->getSyncAssetOf($datum, 'doc_of_artworks'),
            'documentedExhibitions' => $this->getSyncAssetOf($datum, 'doc_of_exhibitions'),
        ];
    }

    private function getSyncAssetOf(Datum $datum, string $pivot_field)
    {
        return $this->getSyncPivots($datum, $pivot_field, 'related_id', function ($pivot) {
            return [
                $pivot->related_id => [
                    'preferred' => $pivot->is_preferred,
                    'is_doc' => $pivot->is_doc,
                ],
            ];
        });
    }
}

<?php

namespace App\Transformers\Inbound\Collections;

use App\Transformers\Datum;
use App\Transformers\Inbound\CollectionsTransformer;

class Asset extends CollectionsTransformer
{

    protected function getIds(Datum $datum)
    {
        return  [
            'lake_guid' => $datum->id,
        ];
    }

    // Unfortunately, NetX does not provide this data:
    // protected function getDates(Datum $datum)
    // {
    //     $dates = parent::getDates($datum);

    //     return array_merge($dates, [
    //         'content_modified_at' => $datum->date('content_modified_at'),
    //     ]);
    // }

    protected function getSync(Datum $datum, $test = false)
    {
        return [
            'imagedArtworks' => $this->getSyncAssetOf($datum, 'rep_of_artworks'),
            'imagedExhibitions' => $this->getSyncAssetOf($datum, 'rep_of_exhibitions'),
            'documentedArtworks' => $this->getSyncAssetOf($datum, 'doc_of_artworks'),
            'documentedExhibitions' => $this->getSyncAssetOf($datum, 'doc_of_exhibitions'),
        ];
    }

    private function getSyncAssetOf(Datum $datum, string $pivot_field)
    {
        return $this->getSyncPivots($datum, $pivot_field, 'related_id', function ($pivot) {
            return [
                $pivot->related_id => [
                    'preferred' => $pivot->is_preferred,
                    'is_doc' => $pivot->is_doc,
                ],
            ];
        });
    }
}

Disable import of `content_modified_at` for assets [WEB-1870]


<?php

/**
 * This file is part of the PierstovalCharacterManagerBundle package.
 *
 * (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pierstoval\Bundle\CharacterManagerBundle\Registry;

use Pierstoval\Bundle\CharacterManagerBundle\Action\StepActionInterface;

class ActionsRegistry
{
    /**
     * @var StepActionInterface[]
     */
    private $actions = [];

    public function addStepAction(StepActionInterface $action): void
    {
        $this->actions[$action->getStep()->getName()] = $action;
    }

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

    public function getAction(string $stepName): StepActionInterface
    {
        if (!array_key_exists($stepName, $this->actions)) {
            throw new \InvalidArgumentException('Step "'.$stepName.'" not found in registry.');
        }

        return $this->actions[$stepName];
    }
}

<?php

/**
 * This file is part of the PierstovalCharacterManagerBundle package.
 *
 * (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Pierstoval\Bundle\CharacterManagerBundle\Registry;

use Pierstoval\Bundle\CharacterManagerBundle\Action\StepActionInterface;

class ActionsRegistry implements ActionsRegistryInterface
{
    /**
     * @var StepActionInterface[][]
     */
    private $actions = [];

    public function addStepAction(string $manager, StepActionInterface $action): void
    {
        $this->actions[$manager][$action->getStep()->getName()] = $action;
    }

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

    public function getAction(string $stepName, string $manager = null): StepActionInterface
    {
        if (!$manager) {
            $manager = array_keys($this->actions)[0];
        }

        if (!isset($this->actions[$manager][$stepName])) {
            throw new \InvalidArgumentException('Step "'.$stepName.'" not found in registry.');
        }

        return $this->actions[$manager][$stepName];
    }
}

Make the Registry use the manager option


<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage MemcachedCli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Memcached\Cli;

class Application extends \In2pire\Cli\CliApplication
{
    /**
     * @inheritdoc
     */
    public function boot()
    {
        if ($this->booted) {
            // Already booted.
            return $this;
        }

        // Boot parent.
        parent::boot();

        // Check memcached extension.
        if (!extension_loaded('memcached')) {
            $this->response->writeln('<error>Could not found memcached extension<error>');
            return false;
        }

        return $this;
    }
}

<?php

/**
 * @file
 *
 * @package In2pire
 * @subpackage MemcachedCli
 * @author Nhat Tran <nhat.tran@inspire.vn>
 */

namespace In2pire\Memcached\Cli;

class Application extends \In2pire\Cli\CliApplication
{
    /**
     * @inheritdoc
     */
    public function boot()
    {
        if ($this->booted) {
            // Already booted.
            return $this;
        }

        // Boot parent.
        parent::boot();

        // Check memcached extension.
        if (!extension_loaded('memcached')) {
            $this->response->writeln('<error>Could not found memcached extension<error>');
            return false;
        }

        $description = $this->runner->getDescription();

        if (!empty($description)) {
            $description .= "\n\n";
        }

        $description .= '<comment>igbinary support</comment>  ' . (\Memcached::HAVE_IGBINARY ? 'yes' : 'no') . "\n";
        $description .= '<comment>json support</comment>      ' . (\Memcached::HAVE_JSON ? 'yes' : 'no');

        $this->runner->setDescription($description);

        return $this;
    }
}

Add more information to application description


<?php

namespace Ddeboer\DocumentManipulationBundle\Document;

use Ddeboer\DocumentManipulationBundle\File\File;
use Ddeboer\DocumentManipulationBundle\Manipulator\ManipulatorChain;

/**
 * Creates a document and passes the manipulator chain to it
 *
 */
class DocumentFactory implements DocumentFactoryInterface
{
    protected $manipulators = array();

    /**
     * Constructor
     *
     * @param ManipulatorChain $manipulators Manipulator chain
     */
    public function __construct(ManipulatorChain $manipulators)
    {
        $this->manipulators = $manipulators;
    }

    /**
     * {@inheritdoc}
     */
    public function open($filename)
    {
        return new Document($this->manipulators, File::fromFilename($filename));
    }

    /**
     * {@inheritdoc}
     */
    public function load($string, $type = null)
    {
        return new Document($this->manipulators, File::fromString($string));
    }
}

<?php

namespace Ddeboer\DocumentManipulationBundle\Document;

use Ddeboer\DocumentManipulationBundle\File\File;
use Ddeboer\DocumentManipulationBundle\Manipulator\ManipulatorChain;

/**
 * Creates a document and passes the manipulator chain to it
 *
 */
class DocumentFactory implements DocumentFactoryInterface
{
    protected $manipulators = array();

    /**
     * Constructor
     *
     * @param ManipulatorChain $manipulators Manipulator chain
     */
    public function __construct(ManipulatorChain $manipulators)
    {
        $this->manipulators = $manipulators;
    }

    /**
     * {@inheritdoc}
     */
    public function open($filename)
    {
        return new Document($this->manipulators, File::fromFilename($filename));
    }

    /**
     * {@inheritdoc}
     */
    public function load($string)
    {
        return new Document($this->manipulators, File::fromString($string));
    }
}

Remove type argument for load()

Remove type argument for load()


<?php
class Kwc_Basic_Image_Crop_ImageComponent extends Kwc_Basic_Image_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['ownModel'] = 'Kwc_Basic_Image_Crop_TestModel';
        $ret['dimensions'] = array(
            array(
                'width' => 500,
                'height' => 500,
                'scale' => Kwf_Media_Image::SCALE_BESTFIT
            )
        );
        $ret['viewCache'] = false;
        return $ret;
    }
}

<?php
class Kwc_Basic_Image_Crop_ImageComponent extends Kwc_Basic_Image_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['ownModel'] = 'Kwc_Basic_Image_Crop_TestModel';
        $ret['dimensions'] = array(
            array(
                'width' => 500,
                'height' => 500,
                'scale' => Kwf_Media_Image::SCALE_BESTFIT
            )
        );
        return $ret;
    }
}

Enable viewcache for test of imagecomponent


<?php

$rootPath = dirname(__FILE__);
require($rootPath . '/protected/components/Environment.php');

$host = $_SERVER['HTTP_HOST'];
$environment = new Environment($host, $rootPath);
$environment->buildConfiguration();
$configPath = $environment->getConfigPath();

$yiiPath = $rootPath . '/../../yii-1.1.11.58da45/framework/yii.php';
require_once($yiiPath);

Yii::createWebApplication($configPath)->run();

<?php

$rootPath = dirname(__FILE__);
require($rootPath . '/protected/components/Environment.php');

$host = $_SERVER['HTTP_HOST'];
$environment = new Environment($host, $rootPath);
$environment->buildConfiguration();
$configPath = $environment->getConfigPath();

$yiiPath = $rootPath . '/../yii-1.1.11.58da45/framework/yii.php';
require_once($yiiPath);

Yii::createWebApplication($configPath)->run();

Update path for yii framework.

Update path for yii framework.


<?php

namespace Jadu\Pulsar\Twig\Extension;

class GetConstantExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->ext = new GetConstantExtension(array());
        define('STRING', 'foo');
        define('BOOL', true);
        define('INT', 42);
        define('NULL', null);
    }

    public function testGetName()
    {
        $this->assertEquals('get_constant_extension', $this->ext->getName());
    }

    public function testGetConstantReturnsNullByDefault()
    {
        $this->assertEquals(null, $this->ext->getConstant());
    }

    public function testGetUndefinedConstantReturnsNull()
    {
        $this->assertEquals(null, $this->ext->getConstant('WAT'));
    }

    public function testGetStringConstantReturnsString()
    {
        $this->assertEquals('foo', $this->ext->getConstant('STRING'));
    }

    public function testGetBoolConstantReturnsBool()
    {
        $this->assertEquals(true, $this->ext->getConstant('BOOL'));
    }

    public function testGetIntConstantReturnsInt()
    {
        $this->assertEquals(42, $this->ext->getConstant('INT'));
    }

    public function testGetNullConstantReturnsNull()
    {
        $this->assertEquals(null, $this->ext->getConstant('NULL'));
    }
}

<?php

namespace Jadu\Pulsar\Twig\Extension;

class GetConstantExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->ext = new GetConstantExtension(array());
        defined('STRING') or define('STRING', 'foo');
        defined('BOOL') or define('BOOL', true);
        defined('INT') or define('INT', 42);
        defined('NULL') or define('NULL', null);
    }

    public function testGetName()
    {
        $this->assertEquals('get_constant_extension', $this->ext->getName());
    }

    public function testGetConstantReturnsNullByDefault()
    {
        $this->assertEquals(null, $this->ext->getConstant());
    }

    public function testGetUndefinedConstantReturnsNull()
    {
        $this->assertEquals(null, $this->ext->getConstant('WAT'));
    }

    public function testGetStringConstantReturnsString()
    {
        $this->assertEquals('foo', $this->ext->getConstant('STRING'));
    }

    public function testGetBoolConstantReturnsBool()
    {
        $this->assertEquals(true, $this->ext->getConstant('BOOL'));
    }

    public function testGetIntConstantReturnsInt()
    {
        $this->assertEquals(42, $this->ext->getConstant('INT'));
    }

    public function testGetNullConstantReturnsNull()
    {
        $this->assertEquals(null, $this->ext->getConstant('NULL'));
    }
}

Stop travis/phpunit complaining about defined constants

Local phpunit didn't throw this error


<?php namespace Modules\Setting\Tests;

use Modules\Core\Tests\BaseTestCase;

abstract class BaseSettingTest extends BaseTestCase
{
    /**
     * @var \Modules\Setting\Repositories\Eloquent\EloquentSettingRepository
     */
    protected $settingRepository;

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

        /** @var \Illuminate\Contracts\Console\Application $artisan */
        $artisan = $this->app->make('Illuminate\Contracts\Console\Application');
        $artisan->call('module:migrate', ['module' => 'Setting']);

        $this->settingRepository = app('Modules\Setting\Repositories\SettingRepository');
    }
}

<?php namespace Modules\Setting\Tests;

use Modules\Core\Tests\BaseTestCase;

abstract class BaseSettingTest extends BaseTestCase
{
    /**
     * @var \Modules\Setting\Repositories\SettingRepository
     */
    protected $settingRepository;

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

        /** @var \Illuminate\Contracts\Console\Application $artisan */
        $artisan = $this->app->make('Illuminate\Contracts\Console\Application');
        $artisan->call('module:migrate', ['module' => 'Setting']);

        $this->settingRepository = app('Modules\Setting\Repositories\SettingRepository');
    }
}

Use the interface in docblock

Use the interface in docblock


<?php
/*
Plugin Name: WooCommerce Komoju Gateway
Plugin URI: https://komoju.com
Description: Extends WooCommerce with Komoju gateway.
Version: 0.1
Author: Komoju
Author URI: https://komoju.com
*/

add_action('plugins_loaded', 'woocommerce_komoju_init', 0);

function woocommerce_komoju_init() {

	if ( !class_exists( 'WC_Payment_Gateway' ) ) return;

	/**
 	 * Localisation
	 */
	//load_plugin_textdomain('wc-komoju', false, dirname( plugin_basename( __FILE__ ) ) . '/languages');

	require_once 'class-wc-gateway-komoju.php';

	/**
 	* Add the Gateway to WooCommerce
 	**/
	function woocommerce_add_komoju_gateway($methods) {
		$methods[] = 'WC_Gateway_Komoju';
		return $methods;
	}

	add_filter('woocommerce_payment_gateways', 'woocommerce_add_komoju_gateway' );
}

<?php
/*
Plugin Name: WooCommerce Komoju Gateway
Plugin URI: https://komoju.com
Description: Extends WooCommerce with Komoju gateway.
Version: 0.1
Author: Komoju
Author URI: https://komoju.com
*/

add_action('plugins_loaded', 'woocommerce_komoju_init', 0);

function woocommerce_komoju_init() {

	if ( !class_exists( 'WC_Payment_Gateway' ) ) return;

	/**
 	 * Localisation
	 */
	load_textdomain( 'woocommerce', WP_PLUGIN_DIR.'/'.dirname( plugin_basename( __FILE__ ) ).'/lang/ja_JP.mo' );

	require_once 'class-wc-gateway-komoju.php';

	/**
 	* Add the Gateway to WooCommerce
 	**/
	function woocommerce_add_komoju_gateway($methods) {
		$methods[] = 'WC_Gateway_Komoju';
		return $methods;
	}

	add_filter('woocommerce_payment_gateways', 'woocommerce_add_komoju_gateway' );
}

Load localization file for the plugin

Load localization file for the plugin