<?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {

  static $has_one = array(
    'MainImage' => 'Image'
  );

  // for rendering thumbnail when linked in facebook
  function getOGImage() {
        return $this->MainImage();
    }

  function getCMSFields() {
    $fields = parent::getCMSFields();
    $fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'));
    $dirname = strtolower($this->ClassName).'s';
    $uf->setFolderName($dirname);
    return $fields;
  }

  public function getPortletTitle() {
    return $this->Title;
  }

  // FIXME - make this more efficient
  public function getPortletImage() {
    $result = null;
    if ($this->MainImageID) {
      $result = DataObject::get_by_id('Image', $this->MainImageID);
    }
    return $result;
  }

  public function getPortletCaption() {
    return '';
  }

}

class PageWithImage_Controller extends Page_Controller {

}

<?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {

  static $has_one = array(
    'MainImage' => 'Image'
  );

  // for rendering thumbnail when linked in facebook
  function getOGImage() {
        return $this->MainImage();
    }

  function getCMSFields() {
    $fields = parent::getCMSFields();
    $imagename = _t('PageWithImage.IMAGE', 'Image');
    $fields->addFieldToTab( 'Root.'.$imagename, $uf = new UploadField('MainImage', _t('PageWithImage.MAIN_IMAGE', 'Main Image')));
    $dirname = strtolower($this->ClassName).'s';
    $uf->setFolderName($dirname);
    return $fields;
  }

  public function getPortletTitle() {
    return $this->Title;
  }

  // FIXME - make this more efficient
  public function getPortletImage() {
    $result = null;
    if ($this->MainImageID) {
      $result = DataObject::get_by_id('Image', $this->MainImageID);
    }
    return $result;
  }

  public function getPortletCaption() {
    return '';
  }

}

class PageWithImage_Controller extends Page_Controller {

}

Allow image tab to be i18n

ENHANCEMENT: Allow image tab to be i18n


<?php

namespace RabbitMQBundle\Tests\Controller;

use AppBundle\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;

class RabbitMQControllerTest extends WebTestCase
{
    protected $entityManager;

    public function __construct()
    {
        self::bootKernel(array('environment' => 'test', 'debug' => 'true'));
        $this->entityManager = self::$kernel->getContainer()->get('doctrine')->getManager();
    }

    public function testRabbitMQ()
    {
        $client = static::createClient();

        $post = new Post();
        $post->setTitle('Lorem ipsum dolor');
        $post->setSlug('Lorem-ipsum-dolor');
        $post->setSummary('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
        $post->setContent('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
        $post->setAuthorEmail('anna_admin@symfony.com');

        $this->entityManager->persist($post);
        $this->entityManager->flush();

        $client->request('POST', '/post/generate_pdf/' . $post->getId());
        $this->assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
        $pdfName = json_decode($client->getResponse()->getContent(), true)['pdfName'];

        $this->entityManager->remove($post);
        $this->entityManager->flush();

        $pdfPath = self::$kernel->getRootDir() . '/../web/downloads/pdf/' . $pdfName . '.pdf';

        sleep(1);
        $this->assertTrue(file_exists($pdfPath));
        unlink($pdfPath);
    }
}

<?php

namespace RabbitMQBundle\Tests\Controller;

use AppBundle\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;

class RabbitMQControllerTest extends WebTestCase
{
    protected $entityManager;

    public function __construct()
    {
        self::bootKernel(array('environment' => 'test', 'debug' => 'true'));
        $this->entityManager = self::$kernel->getContainer()->get('doctrine')->getManager();
    }

    public function testRabbitMQ()
    {
        $client = static::createClient();

        $post = new Post();
        $post->setTitle('Lorem ipsum dolor');
        $post->setSlug('Lorem-ipsum-dolor');
        $post->setSummary('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
        $post->setContent('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
        $post->setAuthorEmail('anna_admin@symfony.com');

        $this->entityManager->persist($post);
        $this->entityManager->flush();

        $client->request('POST', '/post/generate_pdf/' . $post->getId());
        $this->assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
        $pdfName = json_decode($client->getResponse()->getContent(), true)['pdfName'];

        $this->entityManager->remove($post);
        $this->entityManager->flush();

        $pdfPath = self::$kernel->getRootDir() . '/../web/downloads/pdf/' . $pdfName . '.pdf';

        sleep(2);
        $this->assertTrue(file_exists($pdfPath));
        unlink($pdfPath);
    }
}

Increase sleep value to 2s

Increase sleep value to 2s


<?php
/**
 * This file is part of the PHPLucidFrame library.
 * The script executes the command `php lucidframe secret:generate`
 *
 * @package     LucidFrame\Console
 * @since       PHPLucidFrame v 1.11.0
 * @copyright   Copyright (c), PHPLucidFrame.
 * @author      Sithu K. <cithukyaw@gmail.com>
 * @link        http://phplucidframe.sithukyaw.com
 * @license     http://www.opensource.org/licenses/mit-license.php MIT License
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.txt
 */

_consoleCommand('secret:generate')
    ->setDescription('Generate a secret hash key')
    ->addOption('method', 'm', 'The hashing algorithm method (e.g. "md5", "sha256", etc..)', 'md5')
    ->addOption('data', 'd', 'Secret text to be hashed.')
    ->setDefinition(function(\LucidFrame\Console\Command $cmd) {
        $data = $cmd->getOption('data');
        if (!$data) {
            $data = time();
        }

        $secret = hash($cmd->getOption('method'), $data) . "\n";
        $file = INC . '.secret';
        file_put_contents($file, $secret);
    })
    ->register();

<?php
/**
 * This file is part of the PHPLucidFrame library.
 * The script executes the command `php lucidframe secret:generate [options]`
 *
 * @package     LucidFrame\Console
 * @since       PHPLucidFrame v 1.11.0
 * @copyright   Copyright (c), PHPLucidFrame.
 * @author      Sithu K. <cithukyaw@gmail.com>
 * @link        http://phplucidframe.sithukyaw.com
 * @license     http://www.opensource.org/licenses/mit-license.php MIT License
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.txt
 */

_consoleCommand('secret:generate')
    ->setDescription('Generate a secret hash key')
    ->addOption('method', 'm', 'The hashing algorithm method (e.g. "md5", "sha256", etc..)', 'md5')
    ->addOption('data', 'd', 'Secret text to be hashed.')
    ->setDefinition(function(\LucidFrame\Console\Command $cmd) {
        $data = $cmd->getOption('data');
        if (!$data) {
            $data = time();
        }

        $secret = hash($cmd->getOption('method'), $data) . "\n";
        $file = INC . '.secret';
        file_put_contents($file, $secret);
    })
    ->register();

Update file comment block for the command `secret:generate`


<?php
/**
 * @title            Birthday Cron Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / System / Core / Asset / Cron / 24H
 * @version          1.0
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

class BirthdayCoreCron extends Cron
{
    /** @var int */
    private $iNum;

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

        $this->send();
    }

    protected function send()
    {
        $$this->iNum = (new BirthdayCore)->sendMails();

        if ($this->hasBirthdays()) {
            echo t('No birthday today.');
        } else {
            echo nt('%n% email sent.', '%n% emails sent.', $iNum);
        }
    }

    /**
     * @return bool
     */
    private function hasBirthdays()
    {
        return $this->iNum === 0;
    }
}

// Go!
new BirthdayCoreCron;

<?php
/**
 * @title            Birthday Cron Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / System / Core / Asset / Cron / 24H
 * @version          1.0
 */

namespace PH7;

defined('PH7') or exit('Restricted access');

class BirthdayCoreCron extends Cron
{
    /** @var int */
    private $iNum;

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

        $this->send();
    }

    protected function send()
    {
        $this->iNum = (new BirthdayCore)->sendMails();

        if ($this->hasBirthdays()) {
            echo t('No birthday today.');
        } else {
            echo nt('%n% email sent.', '%n% emails sent.', $this->iNum);
        }
    }

    /**
     * @return bool
     */
    private function hasBirthdays()
    {
        return $this->iNum === 0;
    }
}

// Go!
new BirthdayCoreCron;

Fix undefined variable + extra dollar sign $ variable


<?php

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

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

class RoleHierarchyVoterTest extends RoleVoterTest
{
    /**
     * @dataProvider getVoteTests
     */
    public function testVote($roles, $attributes, $expected)
    {
        $voter = new RoleHierarchyVoter(new RoleHierarchy(array('ROLE_FOO' => array('ROLE_FOOBAR'))));

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteTests()
    {
        return array_merge(parent::getVoteTests(), array(
            array(array('ROLE_FOO'), array('ROLE_FOOBAR'), VoterInterface::ACCESS_GRANTED),
        ));
    }
}

<?php

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

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

class RoleHierarchyVoterTest extends RoleVoterTest
{
    /**
     * @dataProvider getVoteTests
     */
    public function testVote($roles, $attributes, $expected)
    {
        $voter = new RoleHierarchyVoter(new RoleHierarchy(array('ROLE_FOO' => array('ROLE_FOOBAR'))));

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteTests()
    {
        return array_merge(parent::getVoteTests(), array(
            array(array('ROLE_FOO'), array('ROLE_FOOBAR'), VoterInterface::ACCESS_GRANTED),
        ));
    }

    /**
     * @dataProvider getVoteWithEmptyHierarchyTests
     */
    public function testVoteWithEmptyHierarchy($roles, $attributes, $expected)
    {
        $voter = new RoleHierarchyVoter(new RoleHierarchy(array()));

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteWithEmptyHierarchyTests()
    {
        return parent::getVoteTests();
    }
}

[SecurityBundle] Fix disabling of RoleHierarchyVoter when passing empty hierarchy


<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace WordPlate\Acf;

use InvalidArgumentException;

/**
 * This is the page class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class Page
{
    /**
     * Create a new page instance.
     *
     * @param array $settings
     *
     * @return void
     */
    public function __construct(array $settings)
    {
        $keys = ['page_title', 'menu_title', 'menu_slug'];

        foreach ($keys as $key) {
            if (!array_key_exists($key, $settings)) {
                throw new InvalidArgumentException("Missing page setting key [$key].");
            }
        }

        $this->settings = $settings;
    }

    /**
     * Return the page as array.
     *
     * @return array
     */
    public function toArray(): array
    {
        return $this->settings;
    }
}

<?php

/*
 * This file is part of WordPlate.
 *
 * (c) Vincent Klaiber <hello@vinkla.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace WordPlate\Acf;

use InvalidArgumentException;

/**
 * This is the page class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class Page
{
    /**
     * Create a new page instance.
     *
     * @param array $settings
     *
     * @return void
     */
    public function __construct(array $settings)
    {
        $keys = ['page_title', 'menu_slug'];

        foreach ($keys as $key) {
            if (!array_key_exists($key, $settings)) {
                throw new InvalidArgumentException("Missing page setting key [$key].");
            }
        }

        $this->settings = $settings;
    }

    /**
     * Return the page as array.
     *
     * @return array
     */
    public function toArray(): array
    {
        return $this->settings;
    }
}

Remove required page key menu_title

Remove required page key menu_title


<?php

namespace Psy;

if (!function_exists('Psy\sh')) {
    /**
     * Command to return the eval-able code to startup PsySH.
     *
     *     eval(\Psy\sh());
     *
     * @return string
     */
    function sh()
    {
        return 'extract(\Psy\Shell::debug(get_defined_vars(), $this ?: null));';
    }
}

<?php

namespace Psy;

if (!function_exists('Psy\sh')) {
    /**
     * Command to return the eval-able code to startup PsySH.
     *
     *     eval(\Psy\sh());
     *
     * @return string
     */
    function sh()
    {
        return 'extract(\Psy\Shell::debug(get_defined_vars(), isset($this) ? $this : null));';
    }
}

Fix warning about undefined $this in Psy\sh()


<?php

class HelloWorldExtension extends Minz_Extension {
	public function init() {
		Minz_View::appendStyle($this->getFileUrl('style.css', 'css'));
		Minz_View::appendScript($this->getFileUrl('script.js', 'js'));

		$this->registerController('hello');
		$this->registerController('index');
		$this->registerViews();

		$this->registerHook('entry_before_insert',
		                    array('HelloWorldExtension', 'setHelloWorldHook'));
	}

	public static function setHelloWorldHook($entry) {
		$entry->_content('Hello world!');
		return $entry;
	}
}

<?php

class HelloWorldExtension extends Minz_Extension {
	public function init() {
		Minz_View::appendStyle($this->getFileUrl('style.css', 'css'));
		Minz_View::appendScript($this->getFileUrl('script.js', 'js'));

		$this->registerController('hello');
		$this->registerController('index');
		$this->registerViews();

		$this->registerHook('entry_before_insert',
		                    array('HelloWorldExtension', 'setHelloWorldContentHook'));
		$this->registerHook('entry_before_display',
		                    array('HelloWorldExtension', 'setHelloWorldTitleHook'));
	}

	public static function setHelloWorldContentHook($entry) {
		$entry->_content('Hello world!');
		return $entry;
	}

	private static $hello_world_title_odd = false;
	public static function setHelloWorldTitleHook($entry) {
		if (self::$hello_world_title_odd) {
			$entry->_title($entry->link());
		}
		self::$hello_world_title_odd = !self::$hello_world_title_odd;
		return $entry;
	}
}

Update with the new entry_before_display hook


<?php
use Migrations\AbstractMigration;

class ReorganizeTranslationTable extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('language_translations');
        $table->removeColumn('is_active');
        $table->removeColumn('code');
        $table->addColumn('language_id', 'string', [
            'limit' => 36,
            'null' => false,
        ]);
        $table->save();
    }
}

<?php
use Migrations\AbstractMigration;

class ReorganizeTranslationTable extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('language_translations');
        if ($table->hasColumn('is_active')) {
            $table->removeColumn('is_active');
        }
        if ($table->hasColumn('code')) {
            $table->removeColumn('code');
        }
        $table->addColumn('language_id', 'string', [
            'limit' => 36,
            'null' => false,
        ]);
        $table->save();
    }
}

Remove columns, only if they already exist


<?php

namespace TheCrypticAce\Suitey\Environment;

use Illuminate\Contracts\Foundation\Application;

final class Environment
{
    public static function loadUsing(Application $app)
    {
        return $app->make(Loader::class)->load(
            $app["config"]["suitey.environments"]
        );
    }

    public static function apply($environment)
    {
        foreach ($environment as $key => $value) {
            putenv("{$key}={$value}");
        }
    }
}

<?php

namespace TheCrypticAce\Suitey\Environment;

use Illuminate\Contracts\Foundation\Application;

final class Environment
{
    public static function loadUsing(Application $app)
    {
        return $app->make(Loader::class)->load(
            $app["config"]["suitey.environments"]
        );
    }

    public static function apply($environment)
    {
        foreach ($environment as $key => $values) {
            foreach ((array) $values as $value) {
                putenv("{$key}={$value}");
            }
        }
    }
}

Handle environments that provide multiple env values


<?php

namespace PragmaRX\Tracker\Support;

use UAParser\Parser;

class UserAgentParser
{
    public $parser;

    public $userAgent;

    public $operatingSystem;

    public $device;

    public $originalUserAgent;

    public function __construct($basePath, $userAgent = null)
    {
        if (!$userAgent && isset($_SERVER['HTTP_USER_AGENT'])) {
            $userAgent = $_SERVER['HTTP_USER_AGENT'];
        }

        $this->parser = Parser::create()->parse($userAgent);

        $this->userAgent = $this->parser->ua;

        $this->operatingSystem = $this->parser->os;

        $this->device = $this->parser->device;

        $this->basePath = $basePath;

        $this->originalUserAgent = $this->parser->originalUserAgent;
    }

    public function getOperatingSystemVersion()
    {
        return    $this->operatingSystem->major.
                ($this->operatingSystem->minor !== null ? '.'.$this->operatingSystem->minor : '').
                ($this->operatingSystem->patch !== null ? '.'.$this->operatingSystem->patch : '');
    }

    public function getUserAgentVersion()
    {
        return  $this->userAgent->major.
                ($this->userAgent->minor !== null ? '.'.$this->userAgent->minor : '').
                ($this->userAgent->patch !== null ? '.'.$this->userAgent->patch : '');
    }
}

<?php

namespace PragmaRX\Tracker\Support;

use UAParser\Parser;

class UserAgentParser
{
    public $parser;

    public $userAgent;

    public $operatingSystem;

    public $device;

    public $originalUserAgent;

    public function __construct($basePath, $userAgent = '')
    {
        if (!$userAgent && isset($_SERVER['HTTP_USER_AGENT'])) {
            $userAgent = $_SERVER['HTTP_USER_AGENT'];
        }

        $this->parser = Parser::create()->parse($userAgent);

        $this->userAgent = $this->parser->ua;

        $this->operatingSystem = $this->parser->os;

        $this->device = $this->parser->device;

        $this->basePath = $basePath;

        $this->originalUserAgent = $this->parser->originalUserAgent;
    }

    public function getOperatingSystemVersion()
    {
        return    $this->operatingSystem->major.
                ($this->operatingSystem->minor !== null ? '.'.$this->operatingSystem->minor : '').
                ($this->operatingSystem->patch !== null ? '.'.$this->operatingSystem->patch : '');
    }

    public function getUserAgentVersion()
    {
        return  $this->userAgent->major.
                ($this->userAgent->minor !== null ? '.'.$this->userAgent->minor : '').
                ($this->userAgent->patch !== null ? '.'.$this->userAgent->patch : '');
    }
}

Change $userAgent parameter from null to empty string


<?php
/*
 This file contains a set of functions that are common to all
 tools of besearcher.

 Author: Fernando Bevilacqua <fernando.bevilacqua@his.se>
 */

function aggredateTaskInfos($theTaskJsonFiles) {
    $aInfos = array();

    foreach($theTaskJsonFiles as $aFile) {
        $aInfo = json_decode(file_get_contents($aFile), true);

        // TODO: get progress and result data from log file
        $aInfos[] = array(
            'commit'        => $aInfo['hash'],
            'permutation'   => $aInfo['permutation'],
            'date'          => date('d-m-Y H:i:s', $aInfo['time']),
            'params'        => $aInfo['params'],
            'cmd'           => $aInfo['cmd'],
            'progress'      => 0,
            'results'       => array(),
            'raw'           => $aInfo
        );
    }

    return $aInfos;
}

function findTasksInfos($theDataDir) {
    $aData = array();
    $aTasks = scandir($theDataDir);

    foreach($aTasks as $aItem) {
        $aPath = $theDataDir . DIRECTORY_SEPARATOR . $aItem;

        if($aItem[0] != '.' && is_dir($aPath)) {
            $aFiles = glob($aPath . DIRECTORY_SEPARATOR . '*.json');
            $aData[$aItem] = aggredateTaskInfos($aFiles);
        }
    }

    return $aData;
}

?>

<?php
/*
 This file contains a set of functions that are common to all
 tools of besearcher.

 Author: Fernando Bevilacqua <fernando.bevilacqua@his.se>
 */

function aggredateTaskInfos($theTaskJsonFiles) {
    $aInfos = array();

    foreach($theTaskJsonFiles as $aFile) {
        $aInfo = json_decode(file_get_contents($aFile), true);
        $aPermutation = $aInfo['permutation'];

        // TODO: get progress and result data from log file
        $aInfos[$aPermutation] = array(
            'commit'        => $aInfo['hash'],
            'permutation'   => $aPermutation,
            'date'          => date('d-m-Y H:i:s', $aInfo['time']),
            'params'        => $aInfo['params'],
            'cmd'           => $aInfo['cmd'],
            'progress'      => 0,
            'results'       => array(),
            'raw'           => $aInfo
        );
    }

    return $aInfos;
}

function findTasksInfos($theDataDir) {
    $aData = array();
    $aTasks = scandir($theDataDir);

    foreach($aTasks as $aItem) {
        $aPath = $theDataDir . DIRECTORY_SEPARATOR . $aItem;

        if($aItem[0] != '.' && is_dir($aPath)) {
            $aFiles = glob($aPath . DIRECTORY_SEPARATOR . '*.json');
            $aData[$aItem] = aggredateTaskInfos($aFiles);
        }
    }

    return $aData;
}

?>

Index aggregated task data using permutation hash


<?php

/*
 * This file is part of the Active Collab Bootstrap project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\Bootstrap\Controller;

use ActiveCollab\Controller\Controller as BaseController;

/**
 * @package ActiveCollab\Bootstrap\Controller
 */
abstract class Controller extends BaseController
{
    use ControllerTrait;
}

<?php

/*
 * This file is part of the Active Collab Bootstrap project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\Bootstrap\Controller;

use ActiveCollab\Controller\Controller as BaseController;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Interfaces\RouteInterface;

abstract class Controller extends BaseController
{
    use ControllerTrait;

    protected function getRouteParam(ServerRequestInterface $request, string $param_name, $default = null)
    {
        $route = $request->getAttribute('route');

        if ($route instanceof RouteInterface) {
            return $route->getArgument($param_name, $default);
        }

        return $default;
    }
}

Add getRouteParam() method to controller


<?php

final class ConpherenceImageData extends ConpherenceConstants {

  const SIZE_ORIG = 'original';
  const SIZE_CROP = 'crop';

  const CROP_WIDTH = 35;
  const CROP_HEIGHT = 35;

}

<?php

final class ConpherenceImageData extends ConpherenceConstants {

  const SIZE_ORIG = 'original';
  const SIZE_CROP = 'crop';

  const CROP_WIDTH = 200;
  const CROP_HEIGHT = 200;

}

Allow Conpherence room images up to 200px

Summary: Provide higher resolution for Conpherence room images. Fixes T11728

Test Plan:
Upload a new photo, see it pulls in 200px image as background.

{F1858660}

Reviewers: epriestley

Reviewed By: epriestley

Subscribers: Korvin

Maniphest Tasks: T11728

Differential Revision: https://secure.phabricator.com/D16659


<?php

return [
    'oracle' => [
        'driver'   => 'oracle',
        'tns'      => env('DB_TNS', ''),
        'host'     => env('DB_HOST', ''),
        'port'     => env('DB_PORT', '1521'),
        'database' => env('DB_DATABASE', ''),
        'username' => env('DB_USERNAME', ''),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => 'AL32UTF8',
        'prefix'   => '',
    ],
];

<?php

return [
    'oracle' => [
        'driver'   => 'oracle',
        'tns'      => env('DB_TNS', ''),
        'host'     => env('DB_HOST', ''),
        'port'     => env('DB_PORT', '1521'),
        'database' => env('DB_DATABASE', ''),
        'username' => env('DB_USERNAME', ''),
        'password' => env('DB_PASSWORD', ''),
        'charset'  => env('DB_CHARSET', 'AL32UTF8'),
        'prefix'   => env('DB_PREFIX', ''),
    ],
];

Add env for charset and prefix on config file.


<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Inanimatt\SiteBuilder\TransformerCompilerPass;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;

(@include_once __DIR__ . '/../vendor/autoload.php') || @include_once __DIR__ . '/../../../autoload.php';

// Set up the service container
$sc = new ContainerBuilder;
$sc->addCompilerPass(new TransformerCompilerPass);

$searchPath = array(__DIR__, __DIR__.'/..');
if (defined('SITEBUILDER_ROOT')) {
    array_unshift($searchPath, SITEBUILDER_ROOT);
}

$locator = new FileLocator($searchPath);
$resolver = new LoaderResolver(array(
    new YamlFileLoader($sc, $locator),
    new IniFileLoader($sc, $locator),
));

$loader = new DelegatingLoader($resolver);
$loader->load('services.yml');

$sc->compile();
return $sc;

<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Inanimatt\SiteBuilder\TransformerCompilerPass;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\Loader\DelegatingLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;

(@include_once __DIR__ . '/../vendor/autoload.php') || @include_once __DIR__ . '/../../../autoload.php';

// Set up the service container
$sc = new ContainerBuilder;
$sc->addCompilerPass(new TransformerCompilerPass);

$searchPath = array(getcwd(), __DIR__, __DIR__.'/..');
if (defined('SITEBUILDER_ROOT')) {
    array_unshift($searchPath, SITEBUILDER_ROOT);
}

$locator = new FileLocator($searchPath);
$resolver = new LoaderResolver(array(
    new YamlFileLoader($sc, $locator),
    new IniFileLoader($sc, $locator),
));

$loader = new DelegatingLoader($resolver);
$loader->load('services.yml');

$sc->compile();
return $sc;

Add CWD to config search path

Add CWD to config search path


@if (isset($breadcrumbs))

		@foreach ($breadcrumbs as $breadcrumb)

					{{ $breadcrumb['text'] }}

		@endforeach

@endif

@if (isset($breadcrumbs))
	{{-- display full breadcrumbs for larger screens --}}

		@foreach ($breadcrumbs as $breadcrumb)

					{{ $breadcrumb['text'] }}

		@endforeach

	{{-- display simple breadcrumbs for mobile screens --}}

		@if (!preg_match('/' . Request::segment(1) . '\/?$/', url()->current()))

				<< Back to {{ ucwords(Request::segment(1)) }}

		@else

				<< Back to Home

		@endif

@endif

Implement simpler breadcrumbs for screens < 768px


<?php namespace Illuminate\Contracts\Auth;

interface Authenticator {

	/**
	 * Determine if the current user is authenticated.
	 *
	 * @return bool
	 */
	public function check();

	/**
	 * Get the currently authenticated user.
	 *
	 * @return \Illuminate\Contracts\Auth\User|null
	 */
	public function user();

	/**
	 * Log a user into the application without sessions or cookies.
	 *
	 * @param  array  $credentials
	 * @return bool
	 */
	public function once(array $credentials = array());

	/**
	 * Attempt to authenticate a user using the given credentials.
	 *
	 * @param  array  $credentials
	 * @param  bool   $remember
	 * @param  bool   $login
	 * @return bool
	 */
	public function attempt(array $credentials = array(), $remember = false, $login = true);

	/**
	 * Validate a user's credentials.
	 *
	 * @param  array  $credentials
	 * @return bool
	 */
	public function validate(array $credentials = array());

	/**
	 * Log a user into the application.
	 *
	 * @param  \Illuminate\Contracts\Auth\User  $user
	 * @param  bool  $remember
	 * @return void
	 */
	public function login(User $user, $remember = false);

	/**
	 * Log the user out of the application.
	 *
	 * @return void
	 */
	public function logout();

}

<?php namespace Illuminate\Contracts\Auth;

interface Authenticator {

	/**
	 * Determine if the current user is authenticated.
	 *
	 * @return bool
	 */
	public function check();

	/**
	 * Get the currently authenticated user.
	 *
	 * @return \Illuminate\Contracts\Auth\User|null
	 */
	public function user();

	/**
	 * Log a user into the application without sessions or cookies.
	 *
	 * @param  array  $credentials
	 * @return bool
	 */
	public function once(array $credentials = array());

	/**
	 * Attempt to authenticate a user using the given credentials.
	 *
	 * @param  array  $credentials
	 * @param  bool   $remember
	 * @param  bool   $login
	 * @return bool
	 */
	public function attempt(array $credentials = array(), $remember = false, $login = true);

	/**
	 * Validate a user's credentials.
	 *
	 * @param  array  $credentials
	 * @return bool
	 */
	public function validate(array $credentials = array());

	/**
	 * Log a user into the application.
	 *
	 * @param  \Illuminate\Contracts\Auth\User  $user
	 * @param  bool  $remember
	 * @return void
	 */
	public function login(User $user, $remember = false);

	/**
	 * Determine if the user was authenticated via "remember me" cookie.
	 *
	 * @return bool
	 */
	public function viaRemember();

	/**
	 * Log the user out of the application.
	 *
	 * @return void
	 */
	public function logout();

}

Add viaRemember to authenticator contract.


    uri() }}">
        present()->image(540, 400) }}" width="{{ $news->image->width }}" height="{{ $news->image->height }}" alt="">

{{ $news->title }}

{{ $news->present()->dateLocalized }}

            @empty(!$news->summary)

{{ $news->summary }}

            @endempty

    uri() }}">
        @empty (!$news->image)
        present()->image(540, 400) }}" width="{{ $news->image->width }}" height="{{ $news->image->height }}" alt="{{ $news->image->alt_attribute }}">
        @endempty

{{ $news->title }}

{{ $news->present()->dateLocalized }}

            @empty(!$news->summary)

{{ $news->summary }}

            @endempty

Check empty image + missing alt attribute.


<?php

namespace LAG\AdminBundle\DependencyInjection;

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

/**
 * Load AdminBundle configuration into the container.
 */
class LAGAdminExtension extends Extension
{
    /**
     * Load the configuration into the container.
     *
     * @param array $configs
     * @param ContainerBuilder $builder
     */
    public function load(array $configs, ContainerBuilder $builder)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

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

        $applicationConfig = [];
        $adminsConfig = [];
        $enableExtraConfig = true;
        $translationPattern = null;

        if (key_exists('application', $config)) {
            if (key_exists('enable_extra_configuration', $config['application'])) {
                $enableExtraConfig = $config['application']['enable_extra_configuration'];
            }
        }
        if (key_exists('admins', $config)) {
            $adminsConfig = $config['admins'];
        }

        $builder->setParameter('lag.admin.enable_extra_configuration', $enableExtraConfig);
        $builder->setParameter('lag.admin.application_configuration', $applicationConfig);
        $builder->setParameter('lag.admins', $adminsConfig);
    }

    /**
     * @return string
     */
    public function getAlias()
    {
        return 'lag_admin';
    }
}

<?php

namespace LAG\AdminBundle\DependencyInjection;

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

/**
 * Load AdminBundle configuration into the container.
 */
class LAGAdminExtension extends Extension
{
    /**
     * Load the configuration into the container.
     *
     * @param array $configs
     * @param ContainerBuilder $builder
     */
    public function load(array $configs, ContainerBuilder $builder)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

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

        $applicationConfig = [];
        $adminsConfig = [];
        $enableExtraConfig = true;
        $translationPattern = null;

        if (key_exists('application', $config)) {
            if (key_exists('enable_extra_configuration', $config['application'])) {
                $enableExtraConfig = $config['application']['enable_extra_configuration'];
            }
            $applicationConfig = $config['application'];
        }
        if (key_exists('admins', $config)) {
            $adminsConfig = $config['admins'];
        }

        $builder->setParameter('lag.admin.enable_extra_configuration', $enableExtraConfig);
        $builder->setParameter('lag.admin.application_configuration', $applicationConfig);
        $builder->setParameter('lag.admins', $adminsConfig);
    }

    /**
     * @return string
     */
    public function getAlias()
    {
        return 'lag_admin';
    }
}

Add missing application configuration setting in the bundle extension


<?php
namespace wcf\data\cronjob\log;
use wcf\data\DatabaseObject;

/**
 * Represents a croniob log.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Data\Cronjob\Log
 *
 * @property-read	integer		$cronjobLogID
 * @property-read	integer		$cronjobID
 * @property-read	integer		$execTime
 * @property-read	integer		$success
 * @property-read	string		$error
 */
class CronjobLog extends DatabaseObject {}

<?php
namespace wcf\data\cronjob\log;
use wcf\data\DatabaseObject;

/**
 * Represents a croniob log.
 *
 * @author	Alexander Ebert
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Data\Cronjob\Log
 *
 * @property-read	integer		$cronjobLogID
 * @property-read	integer		$cronjobID
 * @property-read	integer		$execTime
 * @property-read	integer		$success
 * @property-read	string		$error
 */
class CronjobLog extends DatabaseObject {
	/**
	 * @inheritDoc
	 */
	protected static $databaseTableIndexName = 'cronjobLogID';
}

Fix database table index name of cronjob logs


<?php

namespace HHVMCraft\Core\Networking\Packets;

require "HHVMCraft.Core/Helpers/HexDump.php";
use HHVMCraft\Core\Helpers\Hex;

class PlayerPositionAndLookPacket {
	const id = "0d";

	public $x;
	public $y;
	public $stance;
	public $z;
	public $yaw;
	public $pitch;
	public $onGround;

	public function readPacket($StreamWrapper) {
		$StreamWrapper->readDouble();
		$this->y = $StreamWrapper->readDouble();
		$this->stance = $StreamWrapper->readDouble();
		$this->z = $StreamWrapper->readDouble();
		$this->yaw = $StreamWrapper->readInt();
		$this->pitch = $StreamWrapper->readInt();
		$this->onGround = $StreamWrapper->readBool();
		//		echo " Position: <".$this->x.",".$this->y.",".$this->z."> Yaw: ".$this->yaw." , Pitch: ".$this->pitch."\n";
	}
}

<?php

namespace HHVMCraft\Core\Networking\Packets;

require "HHVMCraft.Core/Helpers/HexDump.php";
use HHVMCraft\Core\Helpers\Hex;

class PlayerPositionAndLookPacket {
	const id = "0d";

	public $x;
	public $y;
	public $stance;
	public $z;
	public $yaw;
	public $pitch;
	public $onGround;

	public function readPacket($StreamWrapper) {
		$this->x = $StreamWrapper->readDouble();
		$this->y = $StreamWrapper->readDouble();
		$this->stance = $StreamWrapper->readDouble();
		$this->z = $StreamWrapper->readDouble();
		$this->yaw = $StreamWrapper->readInt();
		$this->pitch = $StreamWrapper->readInt();
		$this->onGround = $StreamWrapper->readBool();
	}
}

Fix PositionAndLookPacket from not reading double


<?php
$steps->Given('/^the following (\w+) exists:$/', function($world, $blueprint, $table) {
	\machinist\behat\functions\createMachinesFromTable($world, $blueprint, $table);
});
$steps->Give('/^there are no (\w+) machines$/', function($world, $bp) {
	\machinist\Machinist::wipe($bp, true);
});
$steps->Given('/^there are no machines$/', function($world) {
	\machinist\Machinist::wipeAll(true);
});

<?php
$steps->Given('/^the following (\w+) exists:$/', function($world, $blueprint, $table) {
	\machinist\behat\functions\createMachinesFromTable($world, $blueprint, $table);
});
$steps->Given('/^there are no (\w+) machines$/', function($world, $bp) {
	\machinist\Machinist::wipe($bp, true);
});
$steps->Given('/^there are no machines$/', function($world) {
	\machinist\Machinist::wipeAll(true);
});

Fix a spelling error in the old behat1 machinist steps


<?php

namespace Stratify\TwigModule\Extension;

use Stratify\Router\UrlGenerator;
use Twig_Extension;
use Twig_SimpleFunction;

/**
 * Twig extension that registers Stratify-specific functions and helpers.
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class StratifyExtension extends Twig_Extension
{
    /**
     * @var UrlGenerator
     */
    private $urlGenerator;

    public function __construct(UrlGenerator $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;
    }

    public function getFunctions()
    {
        return [
            new Twig_SimpleFunction('path', [$this, 'generatePath']),
        ];
    }

    public function generatePath(string $name, array $parameters = []) : string
    {
        return $this->urlGenerator->generate($name, $parameters);
    }

    public function getName()
    {
        return 'stratify';
    }
}

<?php

namespace Stratify\TwigModule\Extension;

use Interop\Container\ContainerInterface;
use Stratify\Router\UrlGenerator;
use Twig_Extension;
use Twig_SimpleFunction;

/**
 * Twig extension that registers Stratify-specific functions and helpers.
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class StratifyExtension extends Twig_Extension
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getFunctions()
    {
        return [
            new Twig_SimpleFunction('path', [$this, 'generatePath']),
        ];
    }

    public function generatePath(string $name, array $parameters = []) : string
    {
        $urlGenerator = $this->container->get(UrlGenerator::class);
        return $urlGenerator->generate($name, $parameters);
    }

    public function getName()
    {
        return 'stratify';
    }
}

Resolve the dependency lazily to avoid resolving the UrlGenerator (and all Puli) when not used

The container is injected but it's fine because the Twig extension is a glue class…


<?php

namespace ZfcUser\Mapper;

use Zend\Stdlib\Hydrator\ClassMethods;
use ZfcUser\Entity\UserInterface as UserEntityInterface;

class UserHydrator extends ClassMethods
{
    /**
     * Extract values from an object
     *
     * @param  object $object
     * @return array
     * @throws Exception\InvalidArgumentException
     */
    public function extract($object)
    {
        if (!$object instanceof UserEntityInterface) {
            throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
        }
        /* @var $object UserInterface*/
        $data = parent::extract($object);
        $data = $this->mapField('id', 'user_id', $data);
        return $data;
    }

    /**
     * Hydrate $object with the provided $data.
     *
     * @param  array $data
     * @param  object $object
     * @return UserInterface
     * @throws Exception\InvalidArgumentException
     */
    public function hydrate(array $data, $object)
    {
        if (!$object instanceof UserEntityInterface) {
            throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
        }
        $data = $this->mapField('user_id', 'id', $data);
        return parent::hydrate($data, $object);
    }

    protected function mapField($keyFrom, $keyTo, array $array)
    {
        $array[$keyTo] = $array[$keyFrom];
        unset($array[$keyFrom]);
        return $array;
    }
}

<?php

namespace ZfcUser\Mapper;

use Zend\Stdlib\Hydrator\ClassMethods;
use ZfcUser\Entity\UserInterface as UserEntityInterface;

class UserHydrator extends ClassMethods {

    /**
     * Extract values from an object
     *
     * @param  object $object
     * @return array
     * @throws Exception\InvalidArgumentException
     */
    public function extract($object) {
        if (!$object instanceof UserEntityInterface) {
            throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
        }
        /* @var $object UserInterface */
        $data = parent::extract($object);
        if ($data['id'] !== null) {
            $data = $this->mapField('id', 'user_id', $data);
        } else {
            unset($data['id']);
        }
        return $data;
    }

    /**
     * Hydrate $object with the provided $data.
     *
     * @param  array $data
     * @param  object $object
     * @return UserInterface
     * @throws Exception\InvalidArgumentException
     */
    public function hydrate(array $data, $object) {
        if (!$object instanceof UserEntityInterface) {
            throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface');
        }
        $data = $this->mapField('user_id', 'id', $data);
        return parent::hydrate($data, $object);
    }

    protected function mapField($keyFrom, $keyTo, array $array) {
        $array[$keyTo] = $array[$keyFrom];
        unset($array[$keyFrom]);
        return $array;
    }

}

Fix Null Id, on create user Postgresql

Fix Null Id, on create user  Postgresql


<?php

namespace SearchApi\Builders;

use SearchApi\Builders\QueryBuilder;

/**
 * Responsible for building a query string for SolrSearch
 */
class SolrQueryBuilder implements QueryBuilder {
  /**
   * Build a query string from provided search terms and search options.
   * Returns a query string for a SOLR server.
   *
   * @param SearchTerm[]|null $searchTerms Search terms to search
   * @param SearchApi\Models\SearchOptions|null $options Query options
   */
  function build( $searchTerms, $options = null ) {
    $keywordStrings = '';

    error_log( var_dump( $options ) );

    foreach ( $searchTerms as &$word ) {
      $keywordStrings = $keywordStrings . $word->value . '%20';
    }

    return '?q=collector%3A(' . $keywordStrings . ')&wt=json&indent=true';
  }
}

<?php

namespace SearchApi\Builders;

use SearchApi\Builders\QueryBuilder;

/**
 * Responsible for building a query string for SolrSearch
 */
class SolrQueryBuilder implements QueryBuilder {
  /**
   * Build a query string from provided search terms and search options.
   * Returns a query string for a SOLR server.
   *
   * @param SearchTerm[]|null $searchTerms Search terms to search
   * @param SearchApi\Models\SearchOptions|null $options Query options
   */
  function build( $searchTerms, $options = null ) {
    $keywordStrings = '';

    assert( gettype( $options ) === 'NULL' || gettype( $options ) === 'object' );

    foreach ( $searchTerms as &$word ) {
      $keywordStrings = $keywordStrings . $word->value . '%20';
    }

    return '?q=collector%3A(' . $keywordStrings . ')&wt=json&indent=true';
  }
}

Use assert to typecheck options param

Use assert to typecheck options param


<?php namespace Zara4\API\Communication;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class Util {

  const BASE_URL = "http://dev.zara4.com";

  /**
   * Get the url to the given path.
   *
   * @param $path
   * @return string
   */
  public static function url($path) {
    return self::BASE_URL . $path;
  }

  /**
   * Post the given $data to the given $url.
   *
   * @param $url
   * @param $data
   * @return array
   * @throws Exception
   * @throws AccessDeniedException
   */
  public static function post($url, $data) {

    //
    // Attempt Request
    //
    try {
      $client = new Client();
      $res = $client->post($url, $data);
      return json_decode($res->getBody());
    }

    //
    // Error Handling
    //
    catch(RequestException $e) {
      $responseData = json_decode($e->getResponse()->getBody());

      // Client does not have scope permission
      if($responseData->{"error"} == "invalid_scope") {
        throw new AccessDeniedException("The client credentials are not authorised to perform this action. Scope error.");
      }

      // Generic error
      throw new Exception($responseData->{"error_description"});
    }
  }

}

<?php namespace Zara4\API\Communication;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class Util {

  const BASE_URL = "https://zara4.com";

  /**
   * Get the url to the given path.
   *
   * @param $path
   * @return string
   */
  public static function url($path) {
    return self::BASE_URL . $path;
  }

  /**
   * Post the given $data to the given $url.
   *
   * @param $url
   * @param $data
   * @return array
   * @throws Exception
   * @throws AccessDeniedException
   */
  public static function post($url, $data) {

    //
    // Attempt Request
    //
    try {
      $client = new Client();
      $res = $client->post($url, $data);
      return json_decode($res->getBody());
    }

    //
    // Error Handling
    //
    catch(RequestException $e) {
      $responseData = json_decode($e->getResponse()->getBody());

      // Client does not have scope permission
      if($responseData->{"error"} == "invalid_scope") {
        throw new AccessDeniedException("The client credentials are not authorised to perform this action. Scope error.");
      }

      // Generic error
      throw new Exception($responseData->{"error_description"});
    }
  }

}

Update to use zara4.com instead of dev.zara4.com


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

namespace WellCommerce\Bundle\CouponBundle\Tests\Manager;

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

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

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

namespace WellCommerce\Bundle\CouponBundle\Tests\Manager;

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

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

Return types in manager tests

Return types in manager tests


<?php

namespace Chrisgeary92\Pagespeed\Test;

use Chrisgeary92\Pagespeed\Service;

class ServiceTest extends \PHPUnit_Framework_TestCase
{
    /** @test */
    public function it_is_initializable()
    {
        $service = new Service();

        $this->assertInstanceOf('Chrisgeary92\Pagespeed\Service', $service);
    }

    /** @test */
    public function it_can_merge_url_with_optional_query_arguments()
    {
        $service = new Service();

        $return = $service->getArguments('https://google.com', [
            'strategy' => 'desktop',
            'screenshot' => true
        ]);

        $this->assertArrayHasKey('url', $return);
        $this->assertArrayHasKey('strategy', $return);
        $this->assertArrayHasKey('screenshot', $return);
    }

    /** @test */
    public function it_can_successfully_test_a_public_webpage()
    {
        $url = 'https://github.com/chrisgeary92/pagespeed';

        $service = new Service();
        $response = $service->runPagespeed($url);

        $this->assertEquals($url, $response['id']);
        $this->assertEquals(200, $response['responseCode']);
    }

    /** @test */
    public function it_throws_exceptions_for_failed_pagespeed_checks()
    {
        $this->expectException('Chrisgeary92\Pagespeed\PagespeedException');

        $service = new Service();
        $response = $service->runPagespeed('test');
    }
}

<?php

namespace Chrisgeary92\Pagespeed\Test;

use Chrisgeary92\Pagespeed\Service;
use Chrisgeary92\Pagespeed\PagespeedException;

class ServiceTest extends \PHPUnit_Framework_TestCase
{
    /** @test */
    public function it_is_initializable()
    {
        $service = new Service();

        $this->assertInstanceOf(Service::class, $service);
    }

    /** @test */
    public function it_can_merge_url_with_optional_query_arguments()
    {
        $service = new Service();

        $return = $service->getArguments('https://google.com', [
            'strategy' => 'desktop',
            'screenshot' => true
        ]);

        $this->assertArrayHasKey('url', $return);
        $this->assertArrayHasKey('strategy', $return);
        $this->assertArrayHasKey('screenshot', $return);
    }

    /** @test */
    public function it_can_successfully_test_a_public_webpage()
    {
        $url = 'https://github.com/chrisgeary92/pagespeed';

        $service = new Service();
        $response = $service->runPagespeed($url);

        $this->assertEquals($url, $response['id']);
        $this->assertEquals(200, $response['responseCode']);
    }

    /** @test */
    public function it_throws_exceptions_for_failed_pagespeed_checks()
    {
        $this->expectException(PagespeedException::class);

        $service = new Service();
        $response = $service->runPagespeed('test');
    }
}

Update tests to include PHP 5.5 style Class::class calls


<?php

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

class CreateQuotationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('quotations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('context');
            $table->integer('order');
            $table->timestamps();
        });
    }

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

<?php

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

class CreateQuotationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('quotations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('context');
            $table->integer('order')->default(0);
            $table->timestamps();
        });
    }

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

Set default value of order in Quotation

Set default value of order in Quotation


<?php

/* Redirect to HTTPS and refuse to serve HTTP */
if($_SERVER['HTTPS'] != "on"){
  $_SERVER['FULL_URL'] = 'https://';
  if($_SERVER['SERVER_PORT']!='80')
    $_SERVER['FULL_URL'] .=  $_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
  else
    $_SERVER['FULL_URL'] .=  $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
  if($_SERVER['QUERY_STRING']>' '){
    $_SERVER['FULL_URL'] .=  '?'.$_SERVER['QUERY_STRING'];
  }

  header("Location: " . $_SERVER['FULL_URL'], true, 301);
  exit();
} else {
  /* Only use HTTPS for the next year */
  header("Strict-Transport-Security: max-age=31536000");
}

?>

<?php

/* Redirect to HTTPS and refuse to serve HTTP */
if($_SERVER['HTTPS'] != "on"){
  $_SERVER['FULL_URL'] = 'https://';
  if($_SERVER['SERVER_PORT']!='80')
    $_SERVER['FULL_URL'] .=  $_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
  else
    $_SERVER['FULL_URL'] .=  $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
  if($_SERVER['QUERY_STRING']>' '){
    $_SERVER['FULL_URL'] .=  '?'.$_SERVER['QUERY_STRING'];
  }

  header("Location: " . $_SERVER['FULL_URL'], true, 301);
  exit();
} else {
  /* Only use HTTPS for the next year */
  header("Strict-Transport-Security: max-age=31536000");
  header("Content-Security-Policy: upgrade-insecure-requests;");
}

?>

Set a CSP to upgrade all insecure requests

By setting a Content Security Policy, all HTTP requests will be now upgraded by
supported browsers to HTTPS automatically. This will ensure a secure-only
experience.


<?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\DebugBundle\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\VarDumper\Command\ServerDumpCommand;
use Symfony\Component\VarDumper\Server\DumpServer;

/**
 * A placeholder command easing VarDumper server discovery.
 *
 * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
 *
 * @internal
 */
class ServerDumpPlaceholderCommand extends ServerDumpCommand
{
    public function __construct(DumpServer $server = null, array $descriptors = array())
    {
        parent::__construct(new class() extends DumpServer {
            public function __construct()
            {
            }
        }, $descriptors);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        (new SymfonyStyle($input, $output))->getErrorStyle()->warning('In order to use the VarDumper server, set the "debug.dump_destination" config option to "tcp://%env(VAR_DUMPER_SERVER)%"');

        return 8;
    }
}

<?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\DebugBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\VarDumper\Command\ServerDumpCommand;
use Symfony\Component\VarDumper\Server\DumpServer;

/**
 * A placeholder command easing VarDumper server discovery.
 *
 * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
 *
 * @internal
 */
class ServerDumpPlaceholderCommand extends Command
{
    private $replacedCommand;

    public function __construct(DumpServer $server = null, array $descriptors = array())
    {
        $this->replacedCommand = new ServerDumpCommand((new \ReflectionClass(DumpServer::class))->newInstanceWithoutConstructor(), $descriptors);

        parent::__construct();
    }

    protected function configure()
    {
        $this->setDefinition($this->replacedCommand->getDefinition());
        $this->setHelp($this->replacedCommand->getHelp());
        $this->setDescription($this->replacedCommand->getDescription());
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        (new SymfonyStyle($input, $output))->getErrorStyle()->warning('In order to use the VarDumper server, set the "debug.dump_destination" config option to "tcp://%env(VAR_DUMPER_SERVER)%"');

        return 8;
    }
}

Fix server dumper placeholder command

[DebugBundle][VarDumper] Fix server dumper placeholder command


<?php
class Kwc_Advanced_GoogleMap_Component extends Kwc_Advanced_GoogleMapView_Component
{
    public static function getSettings()
    {
        $ret = array_merge(parent::getSettings(), array(
            'componentName' => trlKwfStatic('Google Maps'),
            'ownModel' => 'Kwc_Advanced_GoogleMap_Model',
            'default' => array(
                'zoom' => 8,
                'height' => 300
            ),
        ));
        $ret['componentCategory'] = 'special';
        $ret['generators']['child']['component']['text'] = 'Kwc_Basic_Text_Component';
        $ret['placeholder']['noCoordinates'] = trlKwfStatic('coordinates not entered');
        return $ret;
    }

    protected function _getOptions()
    {
        $row = $this->_getRow();
        $fields = array('coordinates', 'zoom', 'width', 'height', 'zoom_properties',
                'scale', 'satelite', 'overview', 'routing', 'map_type', 'scrollwheel');
        foreach ($fields as $f) {
            $ret[$f] = $row->$f;
        }
        if (!isset($ret['coordinates'])) $ret['coordinates'] = '';
        return $ret;
    }
}

<?php
class Kwc_Advanced_GoogleMap_Component extends Kwc_Advanced_GoogleMapView_Component
{
    public static function getSettings()
    {
        $ret = array_merge(parent::getSettings(), array(
            'componentName' => trlKwfStatic('Google Maps'),
            'ownModel' => 'Kwc_Advanced_GoogleMap_Model',
            'default' => array(
                'zoom' => 8,
                'height' => 300
            ),
        ));
        $ret['componentCategory'] = 'special';
        $ret['generators']['child']['component']['text'] = 'Kwc_Basic_Text_Component';
        $ret['placeholder']['noCoordinates'] = trlKwfStatic('coordinates not entered');
        $ret['assetsAdmin']['dep'][] = 'KwfGoogleMapField';
        return $ret;
    }

    protected function _getOptions()
    {
        $row = $this->_getRow();
        $fields = array('coordinates', 'zoom', 'width', 'height', 'zoom_properties',
                'scale', 'satelite', 'overview', 'routing', 'map_type', 'scrollwheel');
        foreach ($fields as $f) {
            $ret[$f] = $row->$f;
        }
        if (!isset($ret['coordinates'])) $ret['coordinates'] = '';
        return $ret;
    }
}

Add missing dependency for backend

Add missing dependency for backend


<?php

namespace BW\ActiveMenuItemBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('bw_active_menu_item');

        // Here you should define the parameters that are allowed to
        // configure your bundle. See the documentation linked above for
        // more information on that topic.

        return $treeBuilder;
    }
}

<?php

namespace BW\ActiveMenuItemBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('bw_active_menu_item');
        if (\method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->getRootNode();
        } else {
            // BC layer for symfony/config 4.1 and older
            $rootNode = $treeBuilder->root('bw_active_menu_item');
        }

        return $treeBuilder;
    }
}

Fix tree builder without a root node deprecation in Symfony/Config 4.2+


<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/blog", name="blog")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $posts = $em->getRepository('SymfonyDayBlogBundle:Post')->findAll();

        return array('posts' => $posts);
    }

    /**
     * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post")
     * @Template()
     */
    public function postAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id);

        return array('post' => $post);
    }
}

<?php

namespace SymfonyDay\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
     * @Route("/blog", name="blog")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $posts = $em->getRepository('SymfonyDayBlogBundle:Post')->findAll();

        return array('posts' => $posts);
    }

    /**
     * @Route("/blog/{id}", requirements={ "id"="\d+" }, name="post")
     * @Template()
     */
    public function postAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $post = $em->getRepository('SymfonyDayBlogBundle:Post')->find($id);

        if (!$post) {
            throw $this->createNotFoundException(sprintf('The post object identified by #%u does not exist.', $id));
        }

        return array('post' => $post);
    }
}

Return a 404 if there is no post with the provided ID


<?php

namespace PHPOrchestra\ModelBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;

/**
 * Class MediaFolder
 *
 * @ODM\Document(
 *   repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
 * )
 */
class MediaFolder extends Folder implements MediaFolderInterface
{
    /**
     * @var Collection
     *
     * @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
     */
    protected $medias;

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
        $this->medias = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getMedias()
    {
        return $this->medias;
    }

    /**
     * @param MediaInterface $media
     */
    public function addMedia(MediaInterface $media)
    {
        $this->medias->add($media);
    }

    /**
     * @param MediaInterface $media
     */
    public function removeMedia(MediaInterface $media)
    {
        $this->medias->removeElement($media);
    }
}

<?php

namespace PHPOrchestra\ModelBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;

/**
 * Class MediaFolder
 *
 * @ODM\Document(
 *   repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
 * )
 */
class MediaFolder extends Folder implements MediaFolderInterface
{
    /**
     * @var Collection
     *
     * @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
     */
    protected $medias;

    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
        $this->medias = new ArrayCollection();
    }

    /**
     * @return Collection
     */
    public function getMedias()
    {
        return $this->medias;
    }

    /**
     * @param MediaInterface $media
     */
    public function addMedia(MediaInterface $media)
    {
        $this->medias->add($media);
        $media->setMedialFolder($this);
    }

    /**
     * @param MediaInterface $media
     */
    public function removeMedia(MediaInterface $media)
    {
        $this->medias->removeElement($media);
    }
}

Add crud for folder in navigation

Add crud for folder in navigation


<?php

namespace Jmlamo\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Jmlamo\DemoBundle\Entity\Author;

class ValidationController extends Controller
{
    /**
     * @Route("/validation")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/validation/create/{name}")
     */
    public function createAction(Request $request, $name = null)
    {
        $validator = $this->get('validator');
        $session = $request->getSession();

        $author = new Author();

        //for security reasons, we only allow "Jude"
        if ('Jude' == $name) {
            $author->setName($name);
        }

        $errors = $validator->validate($author);

        if (count($errors) > 0) {
            $session->getFlashBag()->add(
                'notice',
                // @see __toString()
                (string) $errors
            );

        } else {
            $session->getFlashBag()->add(
                'notice',
                sprintf('%s is valid !', $author->getName())
            );
        }

        return $this->redirect($this->generateUrl('jmlamo_demo_validation_index'));
    }

}

<?php

namespace Jmlamo\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Jmlamo\DemoBundle\Entity\Author;

class ValidationController extends Controller
{
    /**
     * @Route("/validation")
     * @Template()
     */
    public function indexAction()
    {
        return array();
    }

    /**
     * @Route("/validation/create/{name}")
     */
    public function createAction(Request $request, $name = null)
    {
        $validator = $this->get('validator');
        $session = $request->getSession();

        $author = new Author();
        $author->setName($name);

        $errors = $validator->validate($author);

        if (count($errors) > 0) {
            $session->getFlashBag()->add(
                'notice',
                // @see __toString()
                (string) $errors
            );

        } else {
            $session->getFlashBag()->add(
                'notice',
                sprintf('%s is valid !', $author->getName())
            );
        }

        return $this->redirect($this->generateUrl('jmlamo_demo_validation_index'));
    }

}

Stop checking if name is jude

Stop checking if name is jude


@extends('layouts.app')

@section('content')
    <form class="ui form" action="{{ route('games.store') }}" method="POST">
        {{ csrf_field() }}

                Name: <input name="name" type="text">

                Description: <textarea name="description" rows="2"></textarea>

                Developer:
                <select name="developer_id">
                    @foreach($developers as $developer)
                        <option value="{{ $developer->id }}">
                            {{ $developer->nickname or $developer->name }}
                        </option>
                    @endforeach
                </select>

        <button class="ui primary button" type="submit">Save</button>
    </form>
@endsection

@extends('layouts.app')

@section('content')
    <form class="ui form" action="{{ route('games.store') }}" method="POST">
        {{ csrf_field() }}

                Name: <input name="name" type="text">

                Description: <textarea name="description" rows="2"></textarea>

                Photo: <input name="photo" type="text">

                URL: <input name="url" type="text">

                Developer:
                <select name="developer_id">
                    @foreach($developers as $developer)
                        <option value="{{ $developer->id }}">
                            {{ $developer->nickname or $developer->name }}
                        </option>
                    @endforeach
                </select>

        <button class="ui primary button" type="submit">Save</button>
    </form>
@endsection

Add missing fields in the create game resource.


Pending surveys

			Survey ID
            Description
            Date Scheduled
            Test type
            Accession
            Survey Note

@foreach ($pendingSurveys as $pending)

			id)}}">{{ $pending->id }}
			machine->id) }}">{{ $pending->machine->description }}
			{{ $pending->test_date}}
            {{ $pending->type->test_type}}
			{{ $pending->accession }}
			{{ $pending->notes }}
            id) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine">

@endforeach

Pending surveys

			Survey ID
            Description
            Date Scheduled
            Test type
            Accession
            Survey Note

@foreach ($pendingSurveys as $pending)
    if (is_null($pending->machine)) {
        break;
    }
    else {

			id)}}">{{ $pending->id }}
			machine->id) }}">{{ $pending->machine->description }}
			{{ $pending->test_date}}
            {{ $pending->type->test_type}}
			{{ $pending->accession }}
			{{ $pending->notes }}
            id) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine">

    }
@endforeach

Check for deleted machine when showing pending surveys.

Hopefully a work around for #382


<?php

namespace MageTest\Manager\Attributes\Provider;

/**
 * Trait OverrideAttributes
 *
 * @package spec\MageTest\Manager\Attributes\Provider
 */
trait OverrideAttributes
{
    /**
     *  Overrides previously defined attributes, and optionally adds new
     *
     * @param array $attributes
     * @param bool  $appendNew
     * @return mixed
     */
    public function overrideAttributes(array $attributes, $appendNew = true)
    {
        $type = $this->getModelType();

        foreach ($this->model[$type]['attributes'] as $key => $value) {
            if (array_key_exists($key, $attributes)) {
                $this->model[$type]['attributes'][$key] = $attributes[$key];
            }
        }
        if ($appendNew) {
            $this->appendNewAttributes($attributes);
        }
    }

    /**
     *  Append new values to the attributes array
     *
     * @param array $attributes
     */
    private function appendNewAttributes(array $attributes)
    {
        $type = $this->getModelType();
        foreach ($attributes as $key => $value) {
            if (!array_key_exists($key, $this->model[$type])) {
                $this->model[$type][$key] = $value;
            }
        }
    }

}

<?php

namespace MageTest\Manager\Attributes\Provider;

/**
 * Trait OverrideAttributes
 *
 * @package spec\MageTest\Manager\Attributes\Provider
 */
trait OverrideAttributes
{
    /**
     *  Overrides previously defined attributes, and optionally adds new
     *
     * @param array $attributes
     * @param bool  $appendNew
     * @return mixed
     */
    public function overrideAttributes(array $attributes, $appendNew = true)
    {
        $type = $this->getModelType();

        foreach ($this->model[$type]['attributes'] as $key => $value) {
            if (array_key_exists($key, $attributes)) {
                $this->model[$type]['attributes'][$key] = $attributes[$key];
            }
        }
        if ($appendNew) {
            $this->appendNewAttributes($attributes);
        }
    }

    /**
     *  Append new values to the attributes array
     *
     * @param array $attributes
     */
    private function appendNewAttributes(array $attributes)
    {
        $type = $this->getModelType();
        foreach ($attributes as $key => $value) {
            if (!array_key_exists($key, $this->model[$type])) {
                $this->model[$type]['attributes'][$key] = $value;
            }
        }
    }

}

Fix bug with appending new attributes

Fix bug with appending new attributes


© Junior Achievement USA® / 13506 West Maple Road, Omaha NE 68164 / Phone: 402-333-6410 / Fax: 402-333-6797

© Junior Achievement of Midlands, Inc.® / 13506 West Maple Road, Suite 101, Omaha, NE 68164 / Phone: 402-333-6410 / Fax: 402-333-6797

Modify org name and address

Modify org name and address


    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>
    {{ $brand or config('app.name', 'Laravel Application') }}

            @if (isset($menu))
                @foreach ($menu as $link)
                    @if (array_key_exists('links', $link))

                            {{ $link['title'] }}

                                @foreach ($link['links'] as $sublink)

{{ $sublink['title'] }}

                                @endforeach

                    @else

{{ $link['title'] }}

                    @endif
                @endforeach
            @endif
            @yield('navigation')
            @yield('secondary_navigation')
            @if (\Auth::check())

{{ \Auth::user()->name }}

            @endif
            @yield('navigation')

Change to navbar-default instead of inverse to allow easier style overrides.


<?php
/**
 * Quafzi_CustomerPaymentFilter_Model_Observer
 *
 * @category    Payment
 * @package     Quafzi_CustomerPaymentFilter
 * @author      Thomas Birke <tbirke@netextreme.de>
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class Quafzi_CustomerPaymentFilter_Model_Observer
{
    public function paymentMethodIsAllowed($observer)
    {
        $checkResult = $observer->getEvent()->getResult();
        $method      = $observer->getEvent()->getMethodInstance();
        $quote       = $observer->getEvent()->getQuote();

        if ($checkResult->isAvailable
            && $quote->getCustomer()
            && $quote->getCustomer()->getId() // customer exists
        ) {
            // if there is no method allowed explicitly, we expect all methods to be allowed
            $allowedMethods = $quote->getCustomer()->getAllowedPaymentMethods();
            if ($allowedMethods) {
                $allowedMethods = explode(',', $allowedMethods);
                if (false === in_array($method->getCode(), $allowedMethods)) {
                    $checkResult->isAvailable = false;
                }
            }
        }
    }
}

<?php
/**
 * Quafzi_CustomerPaymentFilter_Model_Observer
 *
 * @category    Payment
 * @package     Quafzi_CustomerPaymentFilter
 * @author      Thomas Birke <tbirke@netextreme.de>
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
class Quafzi_CustomerPaymentFilter_Model_Observer
{
    public function paymentMethodIsAllowed($observer)
    {
        $checkResult = $observer->getEvent()->getResult();
        $method      = $observer->getEvent()->getMethodInstance();
        $quote       = $observer->getEvent()->getQuote();
        $customer    = Mage::getSingleton('customer/session')->getCustomer();
        if (is_null($customer) || is_null($customer->getId())) {
            if ($quote && $quote->getCustomer() && $quote->getCustomer()->getId()) {
                $customer = $quote->getCustomer();
            }
        }

        if ($checkResult->isAvailable
            && $customer
            && $customer->getId() // customer exists
        ) {
            // if there is no method allowed explicitly, we expect all methods to be allowed
            $allowedMethods = $customer->getAllowedPaymentMethods();
            if ($allowedMethods) {
                $allowedMethods = explode(',', $allowedMethods);
                if (false === in_array($method->getCode(), $allowedMethods)) {
                    $checkResult->isAvailable = false;
                }
            }
        }
    }
}

Allow determining allowed payment methods without having a current quote


<?php

/**
 * Description of ModuleLoader
 *
 * @author Adam Bukowski <abukowski@telaxus.com>
 */
class ModuleLoader {
    const all_modules = ':all:';

    private $lpa;
    private $lpa_count;
    private $lpa_index = 0;
    private $loaded_modules = array();
    private $initialized = false;

    private function init() {
        if (!$this->initialized) {
            $this->initialized = true;
            $this->lpa = ModuleManager::get_load_priority_array();
            $this->lpa_count = count($this->lpa);
            ModuleManager::$not_loaded_modules = $this->lpa;
            ModuleManager::$loaded_modules = array();
            ModulesAutoloader::enable();
        }
    }

    function load($modules) {
        $this->init();

        if (!is_array($modules))
            $modules = array($modules);

        foreach ($modules as $m) {
            if (array_key_exists($m, ModuleManager::$modules))
                continue;

            while ($this->lpa_index < $this->lpa_count) {
                $row = $this->lpa[$this->lpa_index++];
                $module = $row['name'];
                $version = $row['version'];
                ModuleManager :: include_common($module, $version);
                ModuleManager :: register($module, $version, ModuleManager::$modules);
                if ($m != self::all_modules && $module == $m)
                    break;
            }
        }
    }

}

?>

<?php

/**
 * Description of ModuleLoader
 *
 * @author Adam Bukowski <abukowski@telaxus.com>
 */
class ModuleLoader {
    const all_modules = ':all:';

    private $lpa;
    private $lpa_count;
    private $lpa_index = 0;
    private $loaded_modules = array();
    private $initialized = false;

    private function init() {
        if (!$this->initialized) {
            $this->initialized = true;
            $this->lpa = ModuleManager::get_load_priority_array();
            $this->lpa_count = count($this->lpa);
            ModulesAutoloader::enable();
        }
    }

    function load($modules) {
        $this->init();

        if (!is_array($modules))
            $modules = array($modules);

        foreach ($modules as $m) {
            if (array_key_exists($m, ModuleManager::$modules))
                continue;

            while ($this->lpa_index < $this->lpa_count) {
                $row = $this->lpa[$this->lpa_index++];
                $module = $row['name'];
                $version = $row['version'];
                ModuleManager :: include_common($module, $version);
                ModuleManager :: register($module, $version, ModuleManager::$modules);
                if ($m != self::all_modules && $module == $m)
                    break;
            }
        }
    }

}

?>

Adjust /admin panel to changes in module manager class.


<?php
namespace SBLayout\Model\Page;
use SBLayout\Model\Application;
use SBLayout\Model\Page\Content\Contents;

/**
 * Defines a page displaying arbitrary contents in one or more content sections.
 */
class ContentPage extends Page
{
	/** A content object storing properties of the content sections of a page */
	public $contents;

	/**
	 * Creates a new ContentPage instance
	 *
	 * @param string $title Title of the page that is used as a label in a menu section
	 * @param Contents $contents A content object storing properties of the content sections of a page
	 */
	public function __construct($title, Contents $contents)
	{
		parent::__construct($title);
		$this->contents = $contents;
	}

	/**
	 * @see Page::checkVisibility()
	 */
	public function checkVisibility()
	{
		return true;
	}

	/**
	 * @see Page::checkAccessibility()
	 */
	public function checkAccessibility()
	{
		return true;
	}

	/**
	 * @see Page::lookupSubPage()
	 */
	public function lookupSubPage(Application $application, array $ids, $index = 0)
	{
		if(count($ids) == $index)
		{
			if($this->checkAccessibility())
				return $this;
			else
				throw new PageForbiddenException();
		}
		else
			throw new PageNotFoundException(); // A ContentPage does not refer to sub pages
	}
}
?>

<?php
namespace SBLayout\Model\Page;
use SBLayout\Model\Application;
use SBLayout\Model\PageForbiddenException;
use SBLayout\Model\PageNotFoundException;
use SBLayout\Model\Page\Content\Contents;

/**
 * Defines a page displaying arbitrary contents in one or more content sections.
 */
class ContentPage extends Page
{
	/** A content object storing properties of the content sections of a page */
	public $contents;

	/**
	 * Creates a new ContentPage instance
	 *
	 * @param string $title Title of the page that is used as a label in a menu section
	 * @param Contents $contents A content object storing properties of the content sections of a page
	 */
	public function __construct($title, Contents $contents)
	{
		parent::__construct($title);
		$this->contents = $contents;
	}

	/**
	 * @see Page::checkVisibility()
	 */
	public function checkVisibility()
	{
		return true;
	}

	/**
	 * @see Page::checkAccessibility()
	 */
	public function checkAccessibility()
	{
		return true;
	}

	/**
	 * @see Page::lookupSubPage()
	 */
	public function lookupSubPage(Application $application, array $ids, $index = 0)
	{
		if(count($ids) == $index)
		{
			if($this->checkAccessibility())
				return $this;
			else
				throw new PageForbiddenException();
		}
		else
			throw new PageNotFoundException(); // A ContentPage does not refer to sub pages
	}
}
?>

Fix problem with exception classes

Fix problem with exception classes


<?php namespace GW2Heroes\Console;

use GW2Heroes\Updater\Items\ItemUpdater;
use GW2Heroes\Updater\Specializations\SpecializationUpdater;
use GW2Heroes\Updater\Traits\TraitUpdater;
use GW2Heroes\Updater\Updater;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Update::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     *
     * @return void
     */
    protected function schedule(Schedule $schedule) {
        $schedule->command('gw2heroes:update')
            ->everyFiveMinutes()
            ->withoutOverlapping()
            ->sendOutputTo(storage_path('logs/last-update.log'));

        $schedule->call(function() {
            $updater = new Updater();
            $updater->scheduleUpdate(ItemUpdater::class);
            $updater->scheduleUpdate(SpecializationUpdater::class);
            $updater->scheduleUpdate(TraitUpdater::class);
            $updater->queueScheduledUpdates();
        })->everyMinute();
    }
}

<?php namespace GW2Heroes\Console;

use GW2Heroes\Updater\Items\ItemUpdater;
use GW2Heroes\Updater\Specializations\SpecializationUpdater;
use GW2Heroes\Updater\Traits\TraitUpdater;
use GW2Heroes\Updater\Updater;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Update::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     *
     * @return void
     */
    protected function schedule(Schedule $schedule) {
        $schedule->command('gw2heroes:update')
            ->everyFiveMinutes()
            ->withoutOverlapping()
            ->sendOutputTo(storage_path('logs/last-update.log'));

        $schedule->call(function() {
            \Log::info('Start update...');

            $updater = new Updater();
            $updater->scheduleUpdate(ItemUpdater::class);
            $updater->scheduleUpdate(SpecializationUpdater::class);
            $updater->scheduleUpdate(TraitUpdater::class);
            $updater->queueScheduledUpdates();

            \Log::info('finished update...');
        })->everyMinute();
    }
}

Add additional log statements when running cronjob


<?php

$EmailFrom = "";
$EmailTo = "kimmarieallen@gmail.com";
$Subject = "subject of message here";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>

<?php

$EmailFrom = "";
$EmailTo = "kimmarieallen@gmail.com";
$Subject = "";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>

Add my email to the submit php form

Add my email to the submit php form


<?php
require_once(__DIR__ . "/inc/header.php");

$db = get_database();
$sql = "SELECT
            `name`, `url`, `image_url`
        FROM
            `Resource`";
$resource_result = $db->query($sql);
?>

    <?php while ($resource_row = $resource_result->fetch_assoc()): ?>

            <?php
            $image_url = "http://assets.iu.edu/brand/2.x/trident-large.png";
            if (isset($resource_row["image_url"])) {
                $image_url = $resource_row["image_url"];
            }
            ?>
            <img class="resource-image" width="64" src="<?=$image_url?>" />
            <?=$resource_row["name"]?>

                <?=$resource_row["url"]?>

    <?php endwhile; ?>

<?php
require_once(__DIR__ . "/inc/footer.php");
?>

<?php
require_once(__DIR__ . "/inc/header.php");

$db = get_database();
$sql = "SELECT
            `name`, `url`, `image_url`
        FROM
            `Resource`";
$resource_result = $db->query($sql);
?>

    <?php while ($resource_row = $resource_result->fetch_assoc()): ?>

            <?php
            $image_url = "https://assets.iu.edu/brand/2.x/trident-large.png";
            if (isset($resource_row["image_url"])) {
                $image_url = $resource_row["image_url"];
            }
            ?>
            <img class="resource-image" width="64" src="<?=$image_url?>" />
            <?=$resource_row["name"]?>

                <?=$resource_row["url"]?>

    <?php endwhile; ?>

<?php
require_once(__DIR__ . "/inc/footer.php");
?>

Use HTTPS for default resource icon

Use HTTPS for default resource icon


<?php

namespace Rych\Silex\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Rych\Plates\Extension\RoutingExtension;
use Rych\Plates\Extension\SecurityExtension;

class PlatesServiceProvider implements ServiceProviderInterface
{

    public function register(Application $app)
    {
        $app['plates.path'] = null;
        $app['plates.folders'] = array ();

        $app['plates.engine'] = $app->share(function ($app) {
            $engine = new \League\Plates\Engine($app['plates.path']);
            foreach ($app['plates.folders'] as $name => $path) {
                $engine->addFolder($name, $path);
            }

            if (isset($app['url_generator'])) {
                $engine->loadExtension(new RoutingExtension($app['url_generator']));
            }

            if (isset($app['security'])) {
                $engine->loadExtension(new SecurityExtension($app['security']));
            }

            return $engine;
        });

        $app['plates'] = $app->share(function ($app) {
            $plates = $app['plates.engine'];
            $plates->app = $app;

            return $plates;
        });
    }

    public function boot(Application $app)
    {
    }

}

<?php

namespace Rych\Silex\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Rych\Plates\Extension\RoutingExtension;
use Rych\Plates\Extension\SecurityExtension;

class PlatesServiceProvider implements ServiceProviderInterface
{

    public function register(Application $app)
    {
        $app['plates.path'] = null;
        $app['plates.folders'] = array ();

        $app['plates.engine'] = $app->share(function ($app) {
            $engine = new \League\Plates\Engine($app['plates.path']);
            foreach ($app['plates.folders'] as $name => $path) {
                $engine->addFolder($name, $path);
            }

            if (isset($app['url_generator'])) {
                $engine->loadExtension(new RoutingExtension($app['url_generator']));
            }

            if (isset($app['security'])) {
                $engine->loadExtension(new SecurityExtension($app['security']));
            }

            return $engine;
        });

        $app['plates'] = function ($app) {
            $plates      = $app['plates.engine'];
            $plates->addData([
                'app' => $app
            ]);

            return $plates;
        };
    }

    public function boot(Application $app)
    {
    }

}

Use addData() to append the app object to the plates engine


<?php

namespace Tests\MoFlashCards\ResourceBundle\Service;

use MoFlashCards\ResourceBundle\Service\TextToSpeechService;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class TextToSpeechServiceTest extends KernelTestCase
{
    public function testGetAudio()
    {
        static::bootKernel();
        $service = static::$kernel->getContainer()->get('resource.text.to.speech');
        $audio = $service->get('hello')->getAudio();

        // check audio mime type
        $fileInfo = finfo_open();
        $mimeType = finfo_buffer($fileInfo, $audio, FILEINFO_MIME_TYPE);
        finfo_close($fileInfo);
        $this->assertEquals('audio/mpeg', $mimeType, 'Mimetype is audio.');
    }
}

<?php

namespace Tests\MoFlashCards\ResourceBundle\Service;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class TextToSpeechServiceTest extends KernelTestCase
{
    public function testGetAudio()
    {
        static::bootKernel();
        $service = static::$kernel->getContainer()->get('resource.text.to.speech');
        $audio = $service->get('hello')->getAudio();

        // check audio mime type
        $fileInfo = finfo_open();
        $mimeType = finfo_buffer($fileInfo, $audio, FILEINFO_MIME_TYPE);
        finfo_close($fileInfo);
        $this->assertEquals('audio/mpeg', $mimeType, 'Mimetype is audio.');
    }
}

Remove unused use statement from test.

Remove unused use statement from test.


<?php

namespace Xu\Tests\Components;

use xu;

class Hashids_Test extends \WP_UnitTestCase {

    public function test_encode() {
        $hashids = xu( 'hashids' );
        $this->assertEquals( 'o2fXhV', $hashids->encode( 1, 2, 3 ) );
    }

    public function test_decode() {
        $hashids = xu( 'hashids' );
        $id = $hashids->encode( 1, 2, 3 );
        $this->assertEquals( [1, 2, 3], $hashids->decode( $id ) );
    }

    public function test_encode_with_arguments() {
        $hashids = xu( 'hashids', ['this is my salt', 8, 'abcdefghij1234567890'] );
        $this->assertEquals( '514cdi42', $hashids->encode( 1, 2, 3 ) );
    }

    public function test_decode_with_arguments() {
        $hashids = xu( 'hashids', ['this is my salt', 8, 'abcdefghij1234567890'] );
        $id = $hashids->encode( 1, 2, 3 );
        $this->assertEquals( [1, 2, 3], $hashids->decode( $id ) );
    }

}

<?php

namespace Xu\Tests\Components;

use xu;

class Hashids_Test extends \WP_UnitTestCase {

    public function test_encode() {
        $hashids = xu( 'hashids' );
        $this->assertEquals( 'o2fXhV', $hashids->encode( 1, 2, 3 ) );
    }

    public function test_decode() {
        $hashids = xu( 'hashids' );
        $id = $hashids->encode( 1, 2, 3 );
        $this->assertEquals( [1, 2, 3], $hashids->decode( $id ) );
    }

    public function test_encode_with_arguments() {
        $hashids = xu( 'hashids', ['this is my salt', 8, 'abcdefghij1234567890'] );
        $this->assertEquals( '514cdi42', $hashids->encode( 1, 2, 3 ) );
    }

    public function test_decode_with_arguments() {
        $hashids = xu( 'hashids', ['this is my salt', 8, 'abcdefghij1234567890'] );
        $id = $hashids->encode( 1, 2, 3 );
        $this->assertEquals( [1, 2, 3], $hashids->decode( $id ) );
    }

    public function test_register() {
        xu()->register_component( 'hashids_test', 'Xu\\Components\\Hashids' );
        $hashids = xu( 'hashids_test' );
        $this->assertEquals( 'o2fXhV', $hashids->encode( 1, 2, 3 ) );
    }

}

Add register test to hashids test

Add register test to hashids test