<?php

/* DEVELOPMENT BRANCH */

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Angrybirds;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    /*public function onBootstrap($e)
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }*/
}

<?php

/* MYFEATURE BRANCH */

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Angrybirds;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    /*public function onBootstrap($e)
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }*/
}

Test changes in myfeature branch

Test changes in myfeature branch


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

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

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

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

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

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

Update email in contact form

Update email in contact form


<?php

namespace AndrewNovikof\Objects;

use Illuminate\Support\ServiceProvider;

/**
 * Class ObjectsServiceProvider
 * @package Objects
 */
class ObjectsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
            ], 'config');

            $this->publishes([
                __DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
                __DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
            ], 'objects');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../resources/config/objects.php',
            'config'
        );
        $this->app->alias('objects', ObjectsService::class);
    }
}

<?php

namespace AndrewNovikof\Objects;

use Illuminate\Support\ServiceProvider;

/**
 * Class ObjectsServiceProvider
 * @package Objects
 */
class ObjectsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__ . '/../resources/config/objects.php' => $this->app->configPath() . '/' . 'objects.php',
            ], 'config');

            $this->publishes([
                __DIR__ . '/../resources/examples/Cats.php' => $this->app->basePath() . '/Examples/Cats.php',
                __DIR__ . '/../resources/examples/Dogs.php' => $this->app->basePath() . '/Examples/Dogs.php',
            ], 'objects');
        }
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__.'/../resources/config/objects.php',
            'config'
        );
        $this->app->bind('objects', ObjectsService::class);
    }
}

Change method 'alias' to 'bind' for provide facade


<?php
/**
 * RuleController.php
 * Copyright (C) 2016 Sander Dorigo
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

namespace FireflyIII\Http\Controllers;

use FireflyIII\Http\Requests;
use View;

/**
 * Class RuleController
 *
 * @package FireflyIII\Http\Controllers
 */
class RuleController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        View::share('title', trans('firefly.rules'));
        View::share('mainTitleIcon', 'fa-random');
    }

    public function index()
    {
        return view('rules.index');
    }
}

<?php
/**
 * RuleController.php
 * Copyright (C) 2016 Sander Dorigo
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

namespace FireflyIII\Http\Controllers;

use FireflyIII\Http\Requests;
use View;

/**
 * Class RuleController
 *
 * @package FireflyIII\Http\Controllers
 */
class RuleController extends Controller
{
    /**
     * RuleController constructor.
     */
    public function __construct()
    {
        parent::__construct();
        View::share('title', trans('firefly.rules'));
        View::share('mainTitleIcon', 'fa-random');
    }

    /**
     * @return View
     */
    public function index()
    {
        return view('rules.index');
    }
}

Add php doc to rule controller.

Add php doc to rule controller.


<?php
namespace Concrete\Core\Backup\ContentImporter\Importer\Routine;

use Concrete\Core\Attribute\Type;
use Concrete\Core\Block\BlockType\BlockType;
use Concrete\Core\Package\Package;
use Concrete\Core\Permission\Category;
use Concrete\Core\Support\Facade\Facade;
use Concrete\Core\Validation\BannedWord\BannedWord;
use Concrete\Core\Package\PackageService;

class ImportPackagesRoutine extends AbstractRoutine
{
    public function getHandle()
    {
        return 'packages';
    }

    public function import(\SimpleXMLElement $sx)
    {
        if (isset($sx->packages)) {
            foreach ($sx->packages->package as $p) {
                $pkg = Package::getByHandle((string) $p['handle']);
                if (!$pkg) {
                    $pkgClass = Package::getClass((string) $p['handle']);
                    if ($pkgClass) {
                        $app = Facade::getFacadeApplication();
                        $service = $app->make(PackageService::class);
                        $service->install($pkgClass, []);
                    }
                }
            }
        }
    }

}

<?php
namespace Concrete\Core\Backup\ContentImporter\Importer\Routine;

use Concrete\Core\Attribute\Type;
use Concrete\Core\Block\BlockType\BlockType;
use Concrete\Core\Package\Package;
use Concrete\Core\Permission\Category;
use Concrete\Core\Support\Facade\Facade;
use Concrete\Core\Validation\BannedWord\BannedWord;
use Concrete\Core\Package\PackageService;

class ImportPackagesRoutine extends AbstractRoutine
{
    public function getHandle()
    {
        return 'packages';
    }

    public function import(\SimpleXMLElement $sx)
    {
        if (isset($sx->packages)) {
            foreach ($sx->packages->package as $p) {
                $pkg = Package::getByHandle((string) $p['handle']);
                if (!$pkg) {
                    $pkgClass = Package::getClass((string) $p['handle']);
                    if ($pkgClass) {
                        $app = Facade::getFacadeApplication();
                        $service = $app->make(PackageService::class);

                        $data = [];

                        if (isset($p['full-content-swap'])) {
                            $data["pkgDoFullContentSwap"] = true;
                        }

                        if (isset($p['content-swap-file'])) {
                            $data["contentSwapFile"] = (string)$p['content-swap-file'];
                        }

                        $service->install($pkgClass, $data);
                    }
                }
            }
        }
    }

}

Add possibility to perform a full content swap when installing packages through CIF file (useful for starting point packages)


<?php
$serverRoot = realpath(__DIR__ . '/../../../../../');

require_once($serverRoot . '/tests/lib/KalturaClient.php');
require_once($serverRoot . '/tests/lib/KalturaPlugins/KalturaEventNotificationClientPlugin.php');

if(!isset($_GET['type']))
{
	$message = "Handler type not defined";
	header("HTTP/1.1 500 Internal Server Error: $message");
	die($message);
}

$log = $serverRoot . '/cache/accept.log';
file_put_contents($log, "

***********************************************************************
Handler type: " . $_GET['type'] . "\n", FILE_APPEND);

switch($_GET['type'])
{
	case 'object':
		$object = unserialize($_POST['data']);
		file_put_contents($log, print_r($object, true), FILE_APPEND);
		break;

	case 'json':
		file_put_contents($log, print_r($_POST['data'], true), FILE_APPEND);
		break;

	case 'xml':
		file_put_contents($log, print_r($_POST['data'], true), FILE_APPEND);
		break;

	case 'fields':
		file_put_contents($log, print_r($_POST, true), FILE_APPEND);
		break;

	case 'text':
		$rawPostData = file_get_contents("php://input");
		file_put_contents($log, $rawPostData, FILE_APPEND);
		break;
}

echo 'OK';

<?php
$serverRoot = realpath(__DIR__ . '/../../../../../');

require_once($serverRoot . '/tests/lib/KalturaClient.php');
require_once($serverRoot . '/tests/lib/KalturaPlugins/KalturaHttpNotificationClientPlugin.php');

if(!isset($_GET['type']))
{
	$message = "Handler type not defined";
	header("HTTP/1.1 500 Internal Server Error: $message");
	die($message);
}

$log = $serverRoot . '/cache/accept.log';
file_put_contents($log, "

***********************************************************************
Handler type: " . $_GET['type'] . "\n", FILE_APPEND);

switch($_GET['type'])
{
	case 'object':
		$object = unserialize($_POST['data']);
		file_put_contents($log, print_r($object, true), FILE_APPEND);
		break;

	case 'json':
		file_put_contents($log, print_r($_POST['data'], true), FILE_APPEND);
		break;

	case 'xml':
		file_put_contents($log, print_r($_POST['data'], true), FILE_APPEND);
		break;

	case 'fields':
		file_put_contents($log, print_r($_POST, true), FILE_APPEND);
		break;

	case 'text':
		$rawPostData = file_get_contents("php://input");
		file_put_contents($log, $rawPostData, FILE_APPEND);
		break;
}

echo 'OK';

Include http notification plugin instead of event notification


<?php namespace Orchestra\Support;

use \Session,
	Laravel\Messages as M;

class Messages extends M {

	/**
	 * Add a message to the collector.
	 *
	 * <code>
	 *		// Add a message for the e-mail attribute
	 *		Message::make('email', 'The e-mail address is invalid.');
	 * </code>
	 *
	 * @static
	 * @param  string  $key
	 * @param  string  $message
	 * @return void
	 */
	public static function make($key, $message)
	{
		$instance = new static();
		$instance->add($key, $message);

		return $instance;
	}

	/**
	 * Retrieve Message instance from Session, the data should be in
	 * serialize, so we need to unserialize it first.
	 *
	 * @static
	 * @access public
	 * @return Messages
	 */
	public static function retrieve()
	{
		$message = null;

		if (Session::has('message'))
		{
			$message = @unserialize(Session::get('message', ''));
		}

		Session::forget('message');

		return $message;
	}

	/**
	 * Compile the instance into serialize
	 *
	 * @access public
	 * @return string   serialize of this instance
	 */
	public function serialize()
	{
		return serialize($this);
	}
}

<?php namespace Orchestra\Support;

use \Session,
	Laravel\Messages as M;

class Messages extends M {

	/**
	 * Add a message to the collector.
	 *
	 * <code>
	 *		// Add a message for the e-mail attribute
	 *		Message::make('email', 'The e-mail address is invalid.');
	 * </code>
	 *
	 * @static
	 * @param  string  $key
	 * @param  string  $message
	 * @return void
	 */
	public static function make($key, $message)
	{
		$instance = new static();
		$instance->add($key, $message);

		return $instance;
	}

	/**
	 * Retrieve Message instance from Session, the data should be in
	 * serialize, so we need to unserialize it first.
	 *
	 * @static
	 * @access public
	 * @return Messages
	 */
	public static function retrieve()
	{
		$message = null;

		if (Session::has('message'))
		{
			$message = @unserialize(Session::get('message', ''));
		}

		Session::forget('message');

		return $message;
	}

	/**
	 * Save current instance to Session flash.
	 *
	 * @access public
	 * @return void
	 */
	public function flash()
	{
		Session::flash('message', $this->serialize());
	}

	/**
	 * Compile the instance into serialize
	 *
	 * @access public
	 * @return string   serialize of this instance
	 */
	public function serialize()
	{
		return serialize($this);
	}
}

Add a save to Session::flash().

Add a save to Session::flash().

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


<?php
/**
 * This file is part of the Ecommerce-Core package
 *
 * @package Ecommerce-Core
 */

/**
 * Traits namespace
 */
namespace Heystack\Ecommerce\Transaction\Traits;

/**
 * Provides an implementation for the Serializable Interface for Transaction Modifiers
 *
 * @copyright  Heyday
 * @author Glenn Bautista <glenn@heyday.co.nz>
 * @package Ecommerce-Core
 */
trait TransactionModifierSerializeTrait
{
    use TransactionModifierHasDataTrait;

    /**
     * Returns a serialized string from the data array
     * @return string
     */
    public function serialize()
    {
        return serialize($this->getData());
    }

    /**
     * Unserializes the data into the data array
     * @param string $data
     * @return void
     */
    public function unserialize($data)
    {
        $this->setData(unserialize($data));
    }
}

<?php
/**
 * This file is part of the Ecommerce-Core package
 *
 * @package Ecommerce-Core
 */

/**
 * Traits namespace
 */
namespace Heystack\Ecommerce\Transaction\Traits;

/**
 * Provides an implementation for the Serializable Interface for Transaction Modifiers
 *
 * @copyright  Heyday
 * @author Glenn Bautista <glenn@heyday.co.nz>
 * @package Ecommerce-Core
 */
trait TransactionModifierSerializeTrait
{
    use TransactionModifierHasDataTrait;

    /**
     * Returns a serialized string from the data array
     * @return string
     */
    public function serialize()
    {
        return \Heystack\Core\serialize($this->getData());
    }

    /**
     * Unserializes the data into the data array
     * @param string $data
     * @return void
     */
    public function unserialize($data)
    {
        $this->setData(\Heystack\Core\unserialize($data));
    }
}

Use the new serialization api

Use the new serialization api


<?php

// Delegate static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server'
    && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))
) {
    return false;
}

chdir(dirname(__DIR__));
require 'vendor/autoload.php';

/** @var \Interop\Container\ContainerInterface $container */
$container = require 'config/container.php';

/** @var \Zend\Expressive\Application $app */
$app = $container->get('Zend\Expressive\Application');
$app->run();

<?php

// Delegate static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server'
    && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))
) {
    return false;
}

//Workaround for https://github.com/prooph/proophessor-do/issues/64
error_reporting(E_ALL & ~E_NOTICE);

chdir(dirname(__DIR__));
require 'vendor/autoload.php';

/** @var \Interop\Container\ContainerInterface $container */
$container = require 'config/container.php';

/** @var \Zend\Expressive\Application $app */
$app = $container->get('Zend\Expressive\Application');
$app->run();

Disable php notices for now

Disable php notices for now


<?php

namespace Swarrot\SwarrotBundle\Event;

use Symfony\Contracts\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\Event as DeprecatedEvent;

if (interface_exists(Event::class)) {
    abstract class SymfonyEvent extends Event
    {

    }
} else {
    /**
     * For BC with Symfony < 4.3
     */
    abstract class SymfonyEvent extends DeprecatedEvent
    {

    }
}

<?php

namespace Swarrot\SwarrotBundle\Event;

use Symfony\Contracts\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\Event as DeprecatedEvent;

if (class_exists(Event::class)) {
    abstract class SymfonyEvent extends Event
    {

    }
} else {
    /**
     * For BC with Symfony < 4.3
     */
    abstract class SymfonyEvent extends DeprecatedEvent
    {

    }
}

Fix bad interface_exists check on class

Fix bad interface_exists check on class


<?php

use Codeception\Util\Fixtures;

/**
 * First user site setup tests
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class FirstUserCest
{
    /** @var array */
    protected $user;

    /**
     * @param \AcceptanceTester $I
     */
    public function _before(\AcceptanceTester $I)
    {
        $this->user = Fixtures::get('users');
    }

    /**
     * @param \AcceptanceTester $I
     */
    public function _after(\AcceptanceTester $I)
    {
    }

    /**
     * Create the first site user
     *
     * @param \AcceptanceTester $I
     */
    public function createFirstUserTest(\AcceptanceTester $I)
    {
        $I->wantTo('create the first user');

        // Ensure we're on the first user page
        $I->amOnPage('/bolt/userfirst');
        $I->see('Please create the first user');

        // Fill in the form and submit
        $I->fillField('form[username]',              $this->user['admin']['username']);
        $I->fillField('form[password]',              $this->user['admin']['password']);
        $I->fillField('form[password_confirmation]', $this->user['admin']['password']);
        $I->fillField('form[email]',                 $this->user['admin']['email']);
        $I->fillField('form[displayname]',           $this->user['admin']['displayname']);

        $I->click('input[type=submit]');
    }
}

<?php

use Codeception\Util\Fixtures;

/**
 * First user site setup tests
 *
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class FirstUserCest
{
    /** @var array */
    protected $user;

    /**
     * @param \AcceptanceTester $I
     */
    public function _before(\AcceptanceTester $I)
    {
        $this->user = Fixtures::get('users');
    }

    /**
     * @param \AcceptanceTester $I
     */
    public function _after(\AcceptanceTester $I)
    {
    }

    /**
     * Create the first site user
     *
     * @param \AcceptanceTester $I
     */
    public function createFirstUserTest(\AcceptanceTester $I)
    {
        $I->wantTo('create the first user');

        // Ensure we're on the first user page
        $I->amOnPage('/bolt/userfirst');
        $I->see('Please create the first user');

        // Fill in the form and submit
        $I->fillField('form[username]',              $this->user['admin']['username']);
        $I->fillField('form[password]',              $this->user['admin']['password']);
        $I->fillField('form[password_confirmation]', $this->user['admin']['password']);
        $I->fillField('form[email]',                 $this->user['admin']['email']);
        $I->fillField('form[displayname]',           $this->user['admin']['displayname']);

        $I->click('input[type=submit]');

        // We should now be logged in an greeted!
        $I->see('Welcome to your new Bolt site');
    }
}

[Tests] Add new first user response to acceptance tests


<?php
/**
 * Copyright 2019 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/storage/README.md
 */

namespace Google\Cloud\Samples\Storage;

# [START storage_list_hmac_keys]
use Google\Cloud\Storage\StorageClient;

/**
 * List HMAC keys.
 *
 * @param string $projectId Google Cloud Project ID.
 *
 */
function list_hmac_keys($projectId)
{
    $storage = new StorageClient();
    // By default hmacKeys will use the projectId used by StorageClient() to list HMAC Keys.
    $hmacKeys = $storage->hmacKeys(['projectId' => $projectId]);

    foreach ($hmacKeys as $hmacKey) {
        printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));
    }
}
# [END storage_list_hmac_keys]

<?php
/**
 * Copyright 2019 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/storage/README.md
 */

namespace Google\Cloud\Samples\Storage;

# [START storage_list_hmac_keys]
use Google\Cloud\Storage\StorageClient;

/**
 * List HMAC keys.
 *
 * @param string $projectId Google Cloud Project ID.
 *
 */
function list_hmac_keys($projectId)
{
    $storage = new StorageClient();
    // By default hmacKeys will use the projectId used by StorageClient() to list HMAC Keys.
    $hmacKeys = $storage->hmacKeys(['projectId' => $projectId]);

    foreach ($hmacKeys as $hmacKey) {
        printf('Service Account Email: %s' . PHP_EOL, $hmacKey['metadata']['serviceAccountEmail']);
        printf('Access Id: %s' . PHP_EOL, $hmacKey['metadata']['accessId']);
    }
}
# [END storage_list_hmac_keys]

Fix metadata print in list hmac keys

Fix metadata print in list hmac keys


<?php

namespace Stripe;

class ApplicationFee extends ApiResource
{
    /**
     * This is a special case because the application fee endpoint has an
     *    underscore in it. The parent `className` function strips underscores.
     *
     * @return string The name of the class.
     */
    public static function className()
    {
        return 'application_fee';
    }

    /**
     * @param string $id The ID of the application fee to retrieve.
     * @param array|string|null $opts
     *
     * @return ApplicationFee
     */
    public static function retrieve($id, $opts = null)
    {
        return self::_retrieve($id, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return Collection of ApplicationFees
     */
    public static function all($params = null, $opts = null)
    {
        return self::_all($params, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return ApplicationFee The refunded application fee.
     */
    public function refund($params = null, $opts = null)
    {
        $url = $this->instanceUrl() . '/refund';
        list($response, $opts) = $this->_request('post', $url, $params, $opts);
        $this->refreshFrom($response, $opts);
        return $this;
    }
}

<?php

namespace Stripe;

class ApplicationFee extends ApiResource
{
    /**
     * This is a special case because the application fee endpoint has an
     *    underscore in it. The parent `className` function strips underscores.
     *
     * @return string The name of the class.
     */
    public static function className()
    {
        return 'application_fee';
    }

    /**
     * @param string $id The ID of the application fee to retrieve.
     * @param array|string|null $opts
     *
     * @return ApplicationFee
     */
    public static function retrieve($id, $opts = null)
    {
        return self::_retrieve($id, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return Collection of ApplicationFees
     */
    public static function all($params = null, $opts = null)
    {
        return self::_all($params, $opts);
    }

    /**
     * @param array|null $params
     * @param array|string|null $opts
     *
     * @return ApplicationFee The refunded application fee.
     */
    public function refund($params = null, $opts = null)
    {
        $url = $this->instanceUrl() . '/refunds';
        list($response, $opts) = $this->_request('post', $url, $params, $opts);
        $this->refreshFrom($response, $opts);
        return $this;
    }
}

Correct URL used for refunding application fees

Fixes #208.

See also stripe/stripe-ruby#351.


<?php
declare(strict_types=1);

namespace Moka\Tests;

abstract class IncompleteAbstractTestClass implements TestInterface
{
    public $public;

    protected $protected;

    private $private;

    public $isTrue;

    public static $getInt;

    public function isTrue(): bool
    {
        return true;
    }

    public function getInt(): int
    {
        return 11;
    }

    public function getSelf(): TestInterface
    {
        return $this;
    }

    public function getCallable(): callable
    {
        return function () {
        };
    }

    public function withArgument(int $argument): int
    {
        return $argument;
    }

    public function withArguments(
        int $required,
        $nullable = null,
        string &$byReference = PHP_EOL,
        FooTestClass $class = null,
        array $array = [3],
        callable $callable = null,
        ...$variadic
    ): int {
        return $required;
    }

    public function throwException(): void
    {
    }

    abstract public function abstractMethod();
}

<?php
declare(strict_types=1);

namespace Moka\Tests;

abstract class IncompleteAbstractTestClass implements TestInterface
{
    public $public;

    protected $protected;

    private $private;

    public $isTrue;

    public static $getInt;

    public function isTrue(): bool
    {
        return true;
    }

    public function getInt(): int
    {
        return 11;
    }

    public function getSelf(): TestInterface
    {
        return $this;
    }

    public function getCallable(): callable
    {
        return function () {
        };
    }

    public function withArgument(int $argument): int
    {
        return $argument;
    }

    public function withArguments(
        int $required,
        $nullable = null,
        string &$byReference = PHP_EOL,
        FooTestClass $class = null,
        array $array = [3],
        callable $callable = null,
        ...$variadic
    ): int {
        return $required;
    }

    public function throwException()
    {
    }

    abstract public function abstractMethod();
}

Remove return type breaking failing test


<?php

namespace common\models\comments;

class AdjacencyListComment extends Comment
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%comment_al}}';
    }

    public static function findByPostInternal($postId)
    {
        $comments = static::find()
            ->select(['id', 'parent_id', 'author_id', 'text', 'created_at'])
            ->where(['post_id' => $postId])
            ->asArray()
            ->all();

        $root = ['id' => null, 'children' => []];
        static::prepareComments($root, $comments);
        unset($comments);

        return $root['children'];
    }

    private static function prepareComments(&$parentNode, &$comments)
    {
        foreach ($comments as $i => &$childNode) {
            if (is_integer($childNode['id'])) {
                continue;
            }
            if (!isset($childNode['children'])) {
                $childNode['children'] = [];
            }
            if ($parentNode['id'] == $childNode['parent_id']) {
                $parentNode['children'][] = &$childNode;

                $childNode['id'] = (integer)$childNode['id'];
                $childNode['parent_id'] = (integer)$childNode['parent_id'];
                $childNode['author_id'] = (integer)$childNode['author_id'];
                $childNode['created_at'] = (integer)$childNode['created_at'];
            }
        }
        foreach ($parentNode['children'] as $i => &$childNode) {
            static::prepareComments($childNode, $comments);
        }
    }
}

<?php

namespace common\models\comments;

class AdjacencyListComment extends Comment
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%comment_al}}';
    }

    public static function findByPostInternal($postId)
    {
        $comments = static::find()
            ->select(['id', 'parent_id', 'author_id', 'text', 'created_at'])
            ->where(['post_id' => $postId])
            ->orderBy('created_at DESC')
            ->asArray()
            ->all();

        $root = ['id' => null, 'children' => []];
        static::prepareComments($root, $comments);
        unset($comments);

        return $root['children'];
    }

    private static function prepareComments(&$parentNode, &$comments, $level = 1)
    {
        foreach ($comments as $i => &$childNode) {
            if (is_integer($childNode['id'])) {
                continue;
            }
            if (!isset($childNode['children'])) {
                $childNode['children'] = [];
            }
            if ($parentNode['id'] == $childNode['parent_id']) {
                $parentNode['children'][] = &$childNode;
                $childNode['level'] = $level;
                $childNode['id'] = (integer)$childNode['id'];
                $childNode['parent_id'] = (integer)$childNode['parent_id'];
                $childNode['author_id'] = (integer)$childNode['author_id'];
                $childNode['created_at'] = (integer)$childNode['created_at'];
            }
        }
        foreach ($parentNode['children'] as $i => &$childNode) {
            static::prepareComments($childNode, $comments, $level + 1);
        }
    }
}

Add level attribute and proper sorting.

Add level attribute and proper sorting.


<?php

/*
 * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace JMS\SerializerBundle\Serializer\Exclusion;

use JMS\SerializerBundle\Metadata\ClassMetadata;
use JMS\SerializerBundle\Metadata\PropertyMetadata;

class GroupsExclusionStrategy implements ExclusionStrategyInterface
{
    private $groups = array();

    public function __construct(array $groups)
    {
        foreach ($groups as $group) {
            $this->groups[$group] = true;
        }
    }

    public function shouldSkipClass(ClassMetadata $metadata)
    {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public function shouldSkipProperty(PropertyMetadata $property)
    {
        if ($this->groups && $property->groups) {
            foreach ($property->groups as $group) {
                if (isset($this->groups[$group])) {
                    return false;
                }
            }
        }
        return true;
    }
}

<?php

/*
 * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace JMS\SerializerBundle\Serializer\Exclusion;

use JMS\SerializerBundle\Metadata\ClassMetadata;
use JMS\SerializerBundle\Metadata\PropertyMetadata;

class GroupsExclusionStrategy implements ExclusionStrategyInterface
{
    private $groups = array();

    public function __construct(array $groups)
    {
        foreach ($groups as $group) {
            $this->groups[$group] = true;
        }
    }

    public function shouldSkipClass(ClassMetadata $metadata)
    {
        return false;
    }

    /**
     * {@inheritDoc}
     */
    public function shouldSkipProperty(PropertyMetadata $property)
    {

        if (!$property->groups) {
            return true;
        }

        foreach ($property->groups as $group) {
            if (isset($this->groups[$group])) {
                return false;
            }
        }

        return true;
    }
}

Make the shouldSkipProperty code more readable


<?php

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

/**
 * Class CreateLaralyticsCustomTable
 */
class CreateLaralyticsCustomTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('laralytics_custom', function (Blueprint $table) {

            $engine = Config::get('database.default');

            $table->increments('id');
            $table->integer('user_id')->index()->nullable();
            $table->string('session', 250)->nullable();
            $table->string('hash', 64)->index();
            $table->string('host', 255)->index();
            $table->string('path', 255);
            $table->string('version', 255)->index()->nullable();
            $table->string('event', 64)->index();
            $table->string('element', 255)->index()->nullable();
            $table->text('data');

            // Auto timestamp for postgreSQL and others
            if ($engine === 'pgsql') {
                $table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)'));
            } else {
                $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            }
        });
    }

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

<?php

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

/**
 * Class CreateLaralyticsCustomTable
 */
class CreateLaralyticsCustomTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('laralytics_custom', function (Blueprint $table) {

            $engine = Config::get('database.default');

            $table->increments('id');
            $table->integer('user_id')->index()->nullable();
            $table->string('session', 250)->nullable();
            $table->string('hash', 64)->index();
            $table->string('host', 255)->index();
            $table->string('path', 255);
            $table->string('version', 255)->index()->nullable();
            $table->string('event', 64)->index();
            $table->integer('x');
            $table->integer('y');
            $table->string('element', 255)->index()->nullable();

            // Auto timestamp for postgreSQL and others
            if ($engine === 'pgsql') {
                $table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)'));
            } else {
                $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            }
        });
    }

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

Add x and y field for laralytics_custme table migration


<?php

namespace Phive\TaskQueue\Tests;

use Phive\TaskQueue\SimpleSerializer;

class SimpleSerializerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var SimpleSerializer
     */
    protected $serializer;

    protected function setUp()
    {
        $this->serializer = new SimpleSerializer();
    }

    /**
     * @dataProvider providerDataToSerialize
     */
    public function testSerialization($raw)
    {
        $serialized = $this->serializer->serialize($raw);

        $this->assertInternalType('string', $serialized);
        $this->assertEquals($raw, $this->serializer->deserialize($serialized));
    }

    public function providerDataToSerialize()
    {
        return [
            [null],
            [false],
            [0],
            ['foo bar'],
            [new \stdClass()],
            [[null, false, 0, 'foo bar', new \stdClass(), []]],
        ];
    }
}

<?php

namespace Phive\TaskQueue\Tests;

use Phive\TaskQueue\SimpleSerializer;

class SimpleSerializerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var SimpleSerializer
     */
    protected $serializer;

    protected function setUp()
    {
        $this->serializer = new SimpleSerializer();
    }

    /**
     * @dataProvider provideDataToSerialize
     */
    public function testSerialization($raw)
    {
        $serialized = $this->serializer->serialize($raw);

        $this->assertInternalType('string', $serialized);
        $this->assertEquals($raw, $this->serializer->deserialize($serialized));
    }

    public function provideDataToSerialize()
    {
        return [
            [null],
            [false],
            [0],
            ['foo bar'],
            [new \stdClass()],
            [[null, false, 0, 'foo bar', new \stdClass(), []]],
        ];
    }
}

Tweak a method name in tests

Tweak a method name in tests


<?php

namespace ParserReflection\Stub;

abstract class ExplicitAbstractClass {}

abstract class ImplicitAbstractClass
{
    abstract function test();
}

final class FinalClass {}

interface SimpleInterface {}

interface InterfaceWithMethod {
    function foo();
}

trait SimpleTrait
{
    function foo() { return __CLASS__; }
}

class SimpleInheritance extends ExplicitAbstractClass {}

abstract class SimpleAbstractInheritance extends ImplicitAbstractClass {}

class ClassWithInterface implements SimpleInterface {}

class ClassWithTrait
{
    use SimpleTrait;
}

class ClassWithTraitAndInterface implements InterfaceWithMethod
{
    use SimpleTrait;
}

class NoCloneable
{
    private function __clone() {}
}

interface AbstractInterface
{
    public function foo();
    public function bar();
}

Add tests for cloneable and abstract interface with methods


<?php

namespace Oro\Bundle\TranslationBundle\ImportExport\Strategy;

use Oro\Bundle\ImportExportBundle\Strategy\Import\ConfigurableAddOrReplaceStrategy;
use Oro\Bundle\TranslationBundle\Entity\Repository\TranslationRepository;
use Oro\Bundle\TranslationBundle\Entity\Translation;

class TranslationResetStrategy extends TranslationImportStrategy
{
    /**
     * @var array
     */
    protected $processedLanguages = [];

    /**
     * @param Translation $entity
     *
     * {@inheritdoc}
     */
    protected function beforeProcessEntity($entity)
    {
        if ($entity instanceof Translation) {
            $locale = $entity->getLocale();
            if ($locale && empty($this->processedLanguages[$locale])) {
                /** @var TranslationRepository $repository */
                $repository = $this->doctrineHelper->getEntityRepositoryForClass($this->entityName);
                $this->context->incrementDeleteCount(
                    $repository->getCountByLocale($locale)
                );

                $repository->deleteByLocale($locale);

                $this->processedLanguages[$locale] = true;
            }
        }

        return parent::beforeProcessEntity($entity);
    }

    /**
     * {@inheritdoc}
     */
    protected function findExistingEntity($entity, array $searchContext = [])
    {
        // no need to search entity
        if (is_a($entity, $this->entityName)) {
            return null;
        }

        return parent::findExistingEntity($entity, $searchContext);
    }

    /**
     * There is no replaced entities during reset
     *
     * {@inheritdoc}
     */
    protected function updateContextCounters($entity)
    {
        $this->context->incrementAddCount();
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\ImportExport\Strategy;

use Oro\Bundle\TranslationBundle\Entity\Repository\TranslationRepository;
use Oro\Bundle\TranslationBundle\Entity\Translation;

class TranslationResetStrategy extends TranslationImportStrategy
{
    /**
     * @var array
     */
    protected $processedLanguages = [];

    /**
     * @param Translation $entity
     *
     * {@inheritdoc}
     */
    protected function beforeProcessEntity($entity)
    {
        if ($entity instanceof Translation) {
            $locale = $entity->getLocale();
            if ($locale && empty($this->processedLanguages[$locale])) {
                /** @var TranslationRepository $repository */
                $repository = $this->doctrineHelper->getEntityRepositoryForClass($this->entityName);
                $this->context->incrementDeleteCount(
                    $repository->getCountByLocale($locale)
                );

                $repository->deleteByLocale($locale);

                $this->processedLanguages[$locale] = true;
            }
        }

        return parent::beforeProcessEntity($entity);
    }

    /**
     * {@inheritdoc}
     */
    protected function findExistingEntity($entity, array $searchContext = [])
    {
        // no need to search entity
        if (is_a($entity, $this->entityName)) {
            return null;
        }

        return parent::findExistingEntity($entity, $searchContext);
    }

    /**
     * There is no replaced entities during reset
     *
     * {@inheritdoc}
     */
    protected function updateContextCounters($entity)
    {
        $this->context->incrementAddCount();
    }
}

BAP-11418: Implement Upload (Import) functionality
- remove not used import


<?php

namespace Forms;

use Events\EventDispatcher;
use Forms\Form;
use Validation\Validator;

class FormFactory
{
    public static function make(Form $formClass)
    {
        return new $formClass(
            new Validator,
            new EventDispatcher
        );
    }
}

<?php

namespace Forms;

use Events\EventDispatcher;
use Forms\Form;
use Validation\Validator;

class FormFactory
{
    public static function make($formClass)
    {
        return new $formClass(
            new Validator,
            new EventDispatcher
        );
    }
}

FIX form factory method signatur

FIX form factory method signatur


<?php namespace willvincent\Rateable;

trait Rateable
{
    /**
     * This model has many ratings.
     *
     * @return Rating
     */
    public function ratings()
    {
        return $this->morphMany('willvincent\Rateable\Rating', 'rateable');
    }

    public function averageRating()
    {
        return $this->ratings()
            ->selectRaw('AVG(rating) as averageRating')
            ->pluck('averageRating');
    }

    public function ratingPercent($max = 5)
    {
        $ratings = $this->ratings();
        $quantity = $ratings->count();
        $total = $ratings->selectRaw('SUM(rating) as total')->pluck('total');
        return $total / (($quantity * $max) / 100);
    }

    public function getAverageRatingAttribute()
    {
        return $this->averageRating();
    }
}

<?php namespace willvincent\Rateable;

trait Rateable
{
    /**
     * This model has many ratings.
     *
     * @return Rating
     */
    public function ratings()
    {
        return $this->morphMany('willvincent\Rateable\Rating', 'rateable');
    }

    public function averageRating()
    {
        return $this->ratings()
            ->selectRaw('AVG(rating) as averageRating')
            ->pluck('averageRating');
    }

    public function sumRating()
    {
        return $this->ratings()
            ->selectRaw('SUM(rating) as sumRating')
            ->pluck('sumRating');
    }

    public function ratingPercent($max = 5)
    {
        $ratings = $this->ratings();
        $quantity = $ratings->count();
        $total = $ratings->selectRaw('SUM(rating) as total')->pluck('total');
        return $total / (($quantity * $max) / 100);
    }

    public function getAverageRatingAttribute()
    {
        return $this->averageRating();
    }

    public function getSumRatingAttribute()
    {
        return $this->sumRating();
    }

}

Add sumRating methods to fetch rating when using +1/-1 style ratings.


<?php

/**
 * Copyright 2016 SURFnet bv
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class SecurityController extends Controller
{
    public function sessionExpiredAction(Request $request)
    {
        $redirectToUrl = $this
            ->get('self_service.security.authentication.session.session_storage')
            ->getCurrentRequestUri();

//        // Return URLs generated by us always include a path (ie. at least a forward slash)
//        // @see https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L878
//        $domain = $request->getSchemeAndHttpHost() . '/';
//        if (strpos($redirectToUrl, $domain) !== 0) {
//            $this->get('logger')->error(
//                'Illegal return-url for redirection after session expired and user was logged out, aborting request'
//            );
//
//            throw new BadRequestHttpException('Invalid return-url given');
//        }

        return $this->render(
            '@SurfnetStepupSelfServiceSelfService/Security/sessionExpired.html.twig',
            ['redirect_to_url' => $redirectToUrl]
        );
    }
}

<?php

/**
 * Copyright 2016 SURFnet bv
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

class SecurityController extends Controller
{
    public function sessionExpiredAction(Request $request)
    {
        $redirectToUrl = $this
            ->get('self_service.security.authentication.session.session_storage')
            ->getCurrentRequestUri();

        return $this->render(
            '@SurfnetStepupSelfServiceSelfService/Security/sessionExpired.html.twig',
            ['redirect_to_url' => $redirectToUrl]
        );
    }
}

Remove comment and unused use statement

Remove comment and unused use statement


<?php

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

use yii\helpers\Html;

$this->title = 'EventKit';
?>

Welcome to EventKit!

This application is under construction.

Get started here

<?php

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

use yii\helpers\Html;

$this->title = 'EventKit';
?>

Welcome to EventKit!

A conference management framework

        <?= Html::a('Get started here', ['site/about'], [
            'class' => 'btn btn-lg btn-primary',
        ])?>

Change frontpage and link it with about page


<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Organisms with given ids
 */
class Organisms extends \WebService {

    /**
     * @param $querydata[ids] array of organism ids
     * @returns array of organisms
     */
    public function execute($querydata) {
        global $db;

        $limit = 5;
        if(in_array('limit', $querydata)){
            $limit = $querydata['limit'];
        }
        $query_get_organisms = <<<EOF
SELECT *
    FROM organism LIMIT $limit
EOF;

        $stm_get_organisms = $db->prepare($query_get_organisms);

        $data = array();

        $stm_get_organisms->execute($limit);

        while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) {
            $data[] = $row;
        }

        return $data;
    }

}

?>

<?php

namespace ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns Organisms with given ids
 */
class Organisms extends \WebService {

    /**
     * @param $querydata[ids] array of organism ids
     * @returns array of organisms
     */
    public function execute($querydata) {
        global $db;

        $limit = 5;
        if(in_array('limit', array_keys($querydata))){
            $limit = $querydata['limit'];
        }
        $query_get_organisms = <<<EOF
SELECT *
    FROM organism LIMIT $limit
EOF;

        $stm_get_organisms = $db->prepare($query_get_organisms);

        $data = array();

        $stm_get_organisms->execute(array($limit));

        while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) {
            $data[] = $row;
        }

        return $data;
    }

}

?>

Add missing array to php webservice

Add missing array to php webservice


<?php

namespace App\Http\Controllers;

use App\Event;
use Carbon\Carbon;
use Illuminate\Http\Request;

class EventsController extends Controller
{
  public function show(Event $event)
  {
    return view('events.show', compact('event'));
  }

  public function index(Request $request)
  {
    $before = $request->get('before');
    $events = $before
      ? Event::before(Carbon::parse($before))->get()
      : Event::upcoming()->paginate();

    return view('events.index', [
      'events' => $events,
      'earliestDate' => $this->getEarliestDate($events, $before),
    ]);
  }

  protected function getEarliestDate($events, $before)
  {
    if (!$events->count()) {
      return $before ? $before : Carbon::now()->format('Y-m-d');
    }

    return $events->min('start_date')->format('Y-m-d');
  }
}

<?php

namespace App\Http\Controllers;

use App\Event;
use Carbon\Carbon;
use Illuminate\Http\Request;

class EventsController extends Controller
{
  public function show(Event $event)
  {
    return view('events.show', compact('event'));
  }

  public function index(Request $request)
  {
    $this->validate($request, ['before' => 'date']);
    $before = $request->get('before');
    $events = $before
      ? Event::before(Carbon::parse($before))->get()
      : Event::upcoming()->paginate();

    return view('events.index', [
      'events' => $events,
      'earliestDate' => $this->getEarliestDate($events, $before),
    ]);
  }

  protected function getEarliestDate($events, $before)
  {
    if (!$events->count()) {
      return $before ? $before : Carbon::now()->format('Y-m-d');
    }

    return $events->min('start_date')->format('Y-m-d');
  }
}

Validate date filter for event

Validate date filter for event


<?php

namespace PragmaRX\Sdk\Core\Migrations;

use Illuminate\Database\Console\Migrations\RollbackCommand as IlluminateRollbackCommand;

class RollbackCommand extends IlluminateRollbackCommand {

	use MigratableTrait;

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		if ( ! $this->confirmToProceed()) return;

		$this->migrator->setConnection($this->input->getOption('database'));

		$pretend = $this->input->getOption('pretend');

		$this->requireServiceMigrations();

		$this->migrator->rollback($pretend);

		$this->cleanTemporaryDirectory();

		// Once the migrator has run we will grab the note output and send it out to
		// the console screen, since the migrator itself functions without having
		// any instances of the OutputInterface contract passed into the class.
		foreach ($this->migrator->getNotes() as $note)
		{
			$this->output->writeln($note);
		}
	}

}

<?php

namespace PragmaRX\Sdk\Core\Migrations;

use Illuminate\Database\Console\Migrations\RollbackCommand as IlluminateRollbackCommand;

class RollbackCommand extends IlluminateRollbackCommand {

	use MigratableTrait;

	/**
	 * Execute the console command.
	 *
	 * @return void
	 */
	public function fire()
	{
		if ( ! $this->confirmToProceed()) return;

		$this->migrator->setConnection($this->input->getOption('database'));

		$pretend = $this->input->getOption('pretend');

        if (! isLaravel53())
        {
            $this->requireServiceMigrations();

            $this->migrator->rollback($pretend);
        }
        else
        {
            $this->migrator->rollback($this->getServicesMigrationPaths(), ['pretend' => $pretend]);
        }

		$this->cleanTemporaryDirectory();

		// Once the migrator has run we will grab the note output and send it out to
		// the console screen, since the migrator itself functions without having
		// any instances of the OutputInterface contract passed into the class.
		foreach ($this->migrator->getNotes() as $note)
		{
			$this->output->writeln($note);
		}
	}

}

Make migrations compatible with L53

Make migrations compatible with L53


<?php

/*
 * This file is part of the PHPBench package
 *
 * (c) Daniel Leech <daniel@dantleech.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace PhpBench\Model;

/**
 * Marker interface for iteration results.
 *
 * Implementations should reflect a particular domain of information, e.g.
 * time, memory, xdebug..
 */
interface ResultInterface
{
    /**
     * Return a new instance based using the given array values.
     *
     */
    public static function fromArray(array $values): ResultInterface;

    /**
     * Return a key value set representing the metrics in this result.
     *
     * This set will be used to serialize the results, f.e. as attributes in an
     * XML element.
     *
     * ```
     * [
     *     'stat_1' => 1234,
     *     'stat_2' => 5678,
     * ]
     * ```
     *
     * If the key of this result is "foo" then the set might be serialized as:
     *
     * ```
     * <iteration foo-stat-1="1234" foo-stat-2="5678"/>
     * ```
     *
     * @retrun array
     */
    public function getMetrics();

    /**
     * Return a short key which should represent this result, f.e. `time`.
     * This key must be unique in the set of all result classes.
     */
    public function getKey(): string;
}

<?php

/*
 * This file is part of the PHPBench package
 *
 * (c) Daniel Leech <daniel@dantleech.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

namespace PhpBench\Model;

/**
 * Marker interface for iteration results.
 *
 * Implementations should reflect a particular domain of information, e.g.
 * time, memory, xdebug..
 */
interface ResultInterface
{
    /**
     * Return a new instance based using the given array values.
     * @param array<string,mixed> $values
     */
    public static function fromArray(array $values): ResultInterface;

    /**
     * Return a key value set representing the metrics in this result.
     *
     * This set will be used to serialize the results, f.e. as attributes in an
     * XML element.
     *
     * ```
     * [
     *     'stat_1' => 1234,
     *     'stat_2' => 5678,
     * ]
     * ```
     *
     * If the key of this result is "foo" then the set might be serialized as:
     *
     * ```
     * <iteration foo-stat-1="1234" foo-stat-2="5678"/>
     * ```
     *
     * @retrun array
     */
    public function getMetrics();

    /**
     * Return a short key which should represent this result, f.e. `time`.
     * This key must be unique in the set of all result classes.
     */
    public function getKey(): string;
}

Add return type to resultInterface

Add return type to resultInterface


<?php

namespace Indigo\Iterators;

/**
 * This is an extension of the SPL AppendIterator.
 *
 * Accepts a Traversable containing Iterators.
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class AppendIterator extends \AppendIterator
{
    /**
     * @param \Traversable $iterators
     */
    public function __construct(\Traversable $iterators)
    {
        iterator_apply($iterators, [$this, 'append']);
    }
}

<?php

namespace Indigo\Iterators;

/**
 * This is an extension of the SPL AppendIterator.
 *
 * Accepts a Traversable containing Iterators.
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class AppendIterator extends \AppendIterator
{
    /**
     * @param \Traversable $iterators
     */
    public function __construct(\Traversable $iterators)
    {
        parent::__construct();

        iterator_apply($iterators, [$this, 'append']);
    }
}

Fix invalid object state error

Fix invalid object state error


<?php

namespace RMiller\BehatSpec;

use Behat\Testwork\ServiceContainer\Extension;
use Behat\Testwork\ServiceContainer\ExtensionManager;
use RMiller\ErrorExtension\ErrorExtension;
use RMiller\PhpSpecExtension\PhpSpecExtension as BehatPhpSpecExtension;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class BehatExtension implements Extension
{
    private $extensions = [];

    public function __construct()
    {
        $this->extensions = [
            new BehatPhpSpecExtension(),
            new ErrorExtension(),
        ];
    }

    public function process(ContainerBuilder $container)
    {
        foreach ($this->extensions as $extension) {
            $extension->process($container);
        }
    }

    public function initialize(ExtensionManager $extensionManager)
    {
        foreach ($this->extensions as $extension) {
            $extension->initialize($extensionManager);
        }
    }

    public function load(ContainerBuilder $container, array $config)
    {
        foreach ($this->extensions as $extension) {
            $extension->load($container, $config);
        }
    }

    public function getConfigKey()
    {
        return 'behatspec';
    }

    public function configure(ArrayNodeDefinition $builder)
    {
        $builder
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('path')->defaultValue('bin/phpspec')->end()
            ->end()
         ->end();
    }
}

<?php

namespace RMiller\BehatSpec;

use Behat\Testwork\ServiceContainer\Extension;
use Behat\Testwork\ServiceContainer\ExtensionManager;
use RMiller\ErrorExtension\ErrorExtension;
use RMiller\PhpSpecExtension\PhpSpecExtension as BehatPhpSpecExtension;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class BehatExtension implements Extension
{
    private $extensions = [];

    public function __construct()
    {
        $this->extensions = [
            new BehatPhpSpecExtension(),
            new ErrorExtension(),
        ];
    }

    public function process(ContainerBuilder $container)
    {
        foreach ($this->extensions as $extension) {
            $extension->process($container);
        }
    }

    public function initialize(ExtensionManager $extensionManager)
    {
        foreach ($this->extensions as $extension) {
            $extension->initialize($extensionManager);
        }
    }

    public function load(ContainerBuilder $container, array $config)
    {
        foreach ($this->extensions as $extension) {
            $extension->load($container, $config);
        }
    }

    public function getConfigKey()
    {
        return 'behatspec';
    }

    public function configure(ArrayNodeDefinition $builder)
    {
        $builder
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('path')->defaultValue('bin/phpspec')->end()
                ->scalarNode('config')->defaultNull()->end()
            ->end()
         ->end();
    }
}

Add 'config' option for PhpSpec

Add 'config' option for PhpSpec


<?php

declare(strict_types=1);

namespace Leevel\Database\Mysql;

use Leevel\Database\Manager;
use Leevel\Database\MysqlPoolConnection;
use Leevel\Database\PoolManager;
use Leevel\Protocol\Pool\IPool;
use Leevel\Protocol\Pool\Pool;

/**
 * MySQL 连接池.
 *
 * @codeCoverageIgnore
 */
class MysqlPool extends Pool implements IPool
{
    /**
     * 数据库连接池管理.
     */
    protected PoolManager $poolManager;

    /**
     * 数据库管理.
     */
    protected Manager $manager;

    /**
     * MySQL 连接.
    */
    protected string $mysqlConnect;

    /**
     * 构造函数.
     */
    public function __construct(Manager $manager, string $mysqlConnect, array $option = [])
    {
        $this->manager = $manager;
        $this->poolManager = $manager->createPoolManager();
        $this->mysqlConnect = $mysqlConnect;
        parent::__construct($option);
    }

    /**
     * {@inheritDoc}
     */
    protected function createConnection(): MysqlPoolConnection
    {
        if ($this->poolManager->inTransactionConnection()) {
            return $this->poolManager->getTransactionConnection();
        }

        $this->manager->extend('mysqlPoolConnection', function (Manager $manager): MysqlPoolConnection {
            return $manager->createMysqlPoolConnection($this->mysqlConnect);
        });

        /** @var \Leevel\Database\MysqlPoolConnection $mysql */
        $mysqlPoolConnection = $this->manager->connect('mysqlPoolConnection', true);
        $mysqlPoolConnection->setShouldRelease(true);

        return $mysqlPoolConnection;
    }
}

<?php

declare(strict_types=1);

namespace Leevel\Database\Mysql;

use Leevel\Database\Manager;
use Leevel\Database\PoolManager;
use Leevel\Protocol\Pool\IConnection;
use Leevel\Protocol\Pool\IPool;
use Leevel\Protocol\Pool\Pool;

/**
 * MySQL 连接池.
 *
 * @codeCoverageIgnore
 */
class MysqlPool extends Pool implements IPool
{
    /**
     * 数据库连接池管理.
     */
    protected PoolManager $poolManager;

    /**
     * 数据库管理.
     */
    protected Manager $manager;

    /**
     * MySQL 连接.
    */
    protected string $mysqlConnect;

    /**
     * 构造函数.
     */
    public function __construct(Manager $manager, string $mysqlConnect, array $option = [])
    {
        $this->manager = $manager;
        $this->poolManager = $manager->createPoolManager();
        $this->mysqlConnect = $mysqlConnect;
        parent::__construct($option);
    }

    /**
     * {@inheritDoc}
     */
    protected function createConnection(): IConnection
    {
        if ($this->poolManager->inTransactionConnection()) {
            return $this->poolManager->getTransactionConnection();
        }

        $this->manager->extend('mysqlPoolConnection', function (Manager $manager): IConnection {
            return $manager->createMysqlPoolConnection($this->mysqlConnect);
        });

        /** @var \Leevel\Database\MysqlPoolConnection $mysql */
        $mysqlPoolConnection = $this->manager->connect('mysqlPoolConnection', true);
        $mysqlPoolConnection->setShouldRelease(true);

        return $mysqlPoolConnection;
    }
}

refactor(database): Fix MySQL pool createConnection return type


<?php
    date_default_timezone_set('America/Chicago');

    $file = $_FILES['uploadedfile']['tmp_name'];
    $names = $_FILES['uploadedfile']['name'];

    $target = $dir.'In/'.$names;
    move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);

    $command = escapeshellcmd("python read.py $target");
    $output = shell_exec($command);
    echo "<pre>";
    print_r($output);
    echo "</pre>";

//  Re-route to directory to download the file.
//    $domain = $_SERVER['HTTP_HOST'];
//    $path = implode("/",$fullPath);
//    $toLogin = 'http://'.$domain.$path."/out";
//    header('Location:'.$toLogin);
?>

<?php
    date_default_timezone_set('America/Chicago');

    $file = $_FILES['uploadedfile']['tmp_name'];
    $names = $_FILES['uploadedfile']['name'];

    $target = $dir.'In/'.$names;
    move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);

    $command = escapeshellcmd("python2.7 read.py $target");
    $output = shell_exec($command);
    echo "<pre>";
    print_r($output);
    echo "</pre>";

//  Re-route to directory to download the file.
//    $domain = $_SERVER['HTTP_HOST'];
//    $path = implode("/",$fullPath);
//    $toLogin = 'http://'.$domain.$path."/out";
//    header('Location:'.$toLogin);
?>

Change python command to python2.7

Change python command to python2.7


<?php
namespace LaravelShipStation\Helpers;

class Orders extends Endpoint
{
    /**
     * Create a single order in ShipStation.
     *
     * @param  array  $order
     * @return array
     */
    public function create($order)
    {
        return $this->post($order, 'createorder');
    }

    /**
     * Does the specified order exist by the given order number?
     *
     * @param  mixed  $orderNumber
     * @return bool
     */
    public function exists($orderNumber)
    {
        $order = $this->get([
            'orderNumber' => $orderNumber
        ]);

        return isset($order->total) && $order->total > 0 ? true : false;
    }

    /**
     * How many orders are awaiting shipment?
     *
     * @return int
     */
    public function awaitingShipmentCount()
    {
        $count = $this->get([
            'orderStatus' => 'awaiting_shipment'
        ]);
        return isset($count->total) ? $count->total : 0;
    }
}

<?php
namespace LaravelShipStation\Helpers;

class Orders extends Endpoint
{
    /**
     * Create a single order in ShipStation.
     *
     * @param  array  $order
     * @return array
     */
    public function create($order)
    {
        return $this->post($order, 'createorder');
    }

    /**
     * Does the specified order exist by the given order number?
     *
     * @param  mixed  $orderNumber
     * @return bool
     */
    public function exists($orderNumber)
    {
        $orders = $this->get([
            'orderNumber' => $orderNumber
        ]);

        foreach ($orders->orders as $order) {
            if ($order->orderNumber == $orderNumber) {
                return true;
            }
        }

        return false;
    }

    /**
     * How many orders are awaiting shipment?
     *
     * @return int
     */
    public function awaitingShipmentCount()
    {
        $count = $this->get([
            'orderStatus' => 'awaiting_shipment'
        ]);
        return isset($count->total) ? $count->total : 0;
    }
}

Fix for order exists helper

Fix for order exists helper

This will return partial matches when using the orderNumber query parameter filter.


<?php

namespace KPhoen\ContactBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class ContactController extends BaseContactController
{
    /**
     * @Template()
     */
    public function contactAction(Request $request)
    {
        list($message, $form) = $this->getContactForm();

        if ($request->isMethod('POST') && ($res = $this->handleContactForm($request, $form, $message)) !== null) {
            return $res;
        }

        return [
            'form' => $form->createView(),
            'route' => 'contact_send',
            'route_args' => [],
        ];
    }
}

<?php

namespace KPhoen\ContactBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class ContactController extends BaseContactController
{
    /**
     * @Template("@KPhoenContact/Contact/contact.html.twig")
     */
    public function contactAction(Request $request)
    {
        list($message, $form) = $this->getContactForm();

        if ($request->isMethod('POST') && ($res = $this->handleContactForm($request, $form, $message)) !== null) {
            return $res;
        }

        return [
            'form' => $form->createView(),
            'route' => 'contact_send',
            'route_args' => [],
        ];
    }
}

Fix for Symfony 2.8, with an explicit (correct-case) template file


<?php

namespace App\Console\Commands;

use App\Notifications\TargetDrawn;
use URLParser;

class FixParticipant extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:participant {url : The URL received by one of the participants to write to their santa} {id : The participant id} {email : The correct email of the participant}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix a participant email';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->setCryptIVFromUrl($this->argument('url'));

        $draw = URLParser::parseByName('dearSanta', $this->argument('url'))->participant->draw;

        $participant = $draw->participants->find($this->argument('id'));
        $participant->email = $this->argument('email');
        $participant->find($this->argument('id'))->save();

        $participant->notifyNow(new TargetDrawn);
        $this->info('Participant mail sent');
    }
}

<?php

namespace App\Console\Commands;

use App\Notifications\TargetDrawn;
use URLParser;

class FixParticipant extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:participant {url : The URL received by one of the participants to write to their santa} {id : The participant id} {email : The correct email of the participant}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix a participant email';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->setCryptIVFromUrl($this->argument('url'));

        $draw = URLParser::parseByName('dearSanta', $this->argument('url'))->participant->draw;

        $participant = $draw->participants->find($this->argument('id'));
        $participant->email = $this->argument('email');
        $participant->save();

        $participant->notifyNow(new TargetDrawn);
        $this->info('Participant mail sent');
    }
}

Fix command fix:participant not saving correctly


<?php
/* ===========================================================================
 * Copyright (c) 2018-2019 Zindex Software
 *
 * Licensed under the MIT License
 * =========================================================================== */

namespace Opis\Closure;

/**
 * Serialize
 *
 * @param $data
 * @return string
 */
function serialize($data)
{
    SerializableClosure::enterContext();
    SerializableClosure::wrapClosures($data);
    $data = \serialize($data);
    SerializableClosure::exitContext();
    return $data;
}

/**
 * Unserialize
 *
 * @param $data
 * @param $options
 * @return mixed
 */
function unserialize($data, array $options = null)
{
    SerializableClosure::enterContext();
    $data = \unserialize($data, $options);
    SerializableClosure::unwrapClosures($data);
    SerializableClosure::exitContext();
    return $data;
}

<?php
/* ===========================================================================
 * Copyright (c) 2018-2019 Zindex Software
 *
 * Licensed under the MIT License
 * =========================================================================== */

namespace Opis\Closure;

/**
 * Serialize
 *
 * @param $data
 * @return string
 */
function serialize($data)
{
    SerializableClosure::enterContext();
    SerializableClosure::wrapClosures($data);
    $data = \serialize($data);
    SerializableClosure::exitContext();
    return $data;
}

/**
 * Unserialize
 *
 * @param $data
 * @param $options
 * @return mixed
 */
function unserialize($data, array $options = null)
{
    SerializableClosure::enterContext();
    if ($options === null || PHP_MAJOR_VERSION < 7) {
        $data = \unserialize($data);
    } else {
        $data = \unserialize($data, $options);
    }
    SerializableClosure::unwrapClosures($data);
    SerializableClosure::exitContext();
    return $data;
}

Check if PHP supports $options

Check if PHP supports $options


<?php

namespace Oro\Bundle\TestFrameworkBundle\Migrations\Schema\v1_9;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroTestFrameworkBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $queries->addPostQuery(new UpdateRelationsExtendConfig());
    }
}

<?php

namespace Oro\Bundle\TestFrameworkBundle\Migrations\Schema\v1_9;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\EntityConfigBundle\Migration\RemoveFieldQuery;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroTestFrameworkBundle implements Migration
{
    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $queries->addPostQuery(new UpdateRelationsExtendConfig());
        $queries->addPostQuery(new RemoveFieldQuery('Oro\Bundle\TestFrameworkBundle\Entity\Item', 'isActive'));
    }
}

BB-7804: Test and merge to master
 - fixed notice in builds of functional tests


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

namespace CalendArt\Adapter\Google\Exception;

use ErrorException;

use GuzzleHttp\Message\Response,
    GuzzleHttp\Exception\ParseException;

/**
 * Whenever the Api returns an unexpected result
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class ApiErrorException extends ErrorException
{
    public function __construct(Response $response)
    {
        try {
            $json    = $response->json();
            $message = $json['error']['message'];
        } catch (ParseException $e) {
            $message = $response->getReasonPhrase();
        }

        parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode());
    }
}

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

namespace CalendArt\Adapter\Google\Exception;

use ErrorException;

use GuzzleHttp\Message\Response,
    GuzzleHttp\Exception\ParseException;

/**
 * Whenever the Api returns an unexpected result
 *
 * @author Baptiste Clavié <baptiste@wisembly.com>
 */
class ApiErrorException extends ErrorException
{
    public function __construct(Response $response)
    {
        try {
            $this->details = $response->json();
            $message = $this->details['error']['message'];
        } catch (ParseException $e) {
            $message = $response->getReasonPhrase();
        }

        parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode());
    }

    public function getDetails()
    {
        return $this->details;
    }
}

[Google] Add the possibility to get more details on an api error


<?php

class Denkmal_Paging_Tag_VenueUserLatest extends Denkmal_Paging_Tag_Abstract {

    /**
     * @param Denkmal_Model_Venue $venue
     * @param DateTime|null       $createdMin
     */
    public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
        if ($createdMin == null) {
            $createdMin = (new DateTime())->sub(new DateInterval('PT1H'));
        }

        $join = 'JOIN `denkmal_model_message` m ON `m`.`id` = `denkmal_model_tag_model`.`modelId` ';
        $join .= 'AND `denkmal_model_tag_model`.`modelType` = ' . Denkmal_Model_Message::getTypeStatic();

        $group = '`denkmal_model_tag_model`.`tagId`';

        $where = '`m`.`venue` = ' . $venue->getId();
        $where .= ' AND `m`.`created` > ' . $createdMin->getTimestamp();
        $where .= ' AND `m`.`user` IS NOT NULL';

        $order = '`m`.`created` DESC, `denkmal_model_tag_model`.tagId ASC';
        $source = new CM_PagingSource_Sql('`denkmal_model_tag_model`.tagId', 'denkmal_model_tag_model', $where, $order, $join, $group);
        $source->enableCacheLocal(100);

        parent::__construct($source);
    }
}

<?php

class Denkmal_Paging_Tag_VenueUserLatest extends Denkmal_Paging_Tag_Abstract {

    /**
     * @param Denkmal_Model_Venue $venue
     * @param DateTime|null       $createdMin
     */
    public function __construct(Denkmal_Model_Venue $venue, DateTime $createdMin = null) {
        if ($createdMin == null) {
            $createdMin = (new DateTime())->sub(new DateInterval('PT1H'));
        }

        $join = 'JOIN `denkmal_model_message` m ON `m`.`id` = `denkmal_model_tag_model`.`modelId` ';
        $join .= 'AND `denkmal_model_tag_model`.`modelType` = ' . Denkmal_Model_Message::getTypeStatic();

        $group = '`denkmal_model_tag_model`.`tagId`';

        $where = '`m`.`venue` = ' . $venue->getId();
        $where .= ' AND `m`.`created` > ' . $createdMin->getTimestamp();

        $order = 'ISNULL(`m`.user) ASC, `m`.`created` DESC, `denkmal_model_tag_model`.tagId ASC';
        $source = new CM_PagingSource_Sql('`denkmal_model_tag_model`.tagId', 'denkmal_model_tag_model', $where, $order, $join, $group);
        $source->enableCacheLocal(100);

        parent::__construct($source);
    }
}

Order tags: users first, guest after

Order tags: users first, guest after


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * Represents a GUID/UUID datatype (both are actually synonyms) in the database.
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since 2.3
 */
class GuidType extends StringType
{
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getGuidTypeDeclarationSQL($fieldDeclaration);
    }

    public function getName()
    {
        return Type::GUID;
    }
}

<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * Represents a GUID/UUID datatype (both are actually synonyms) in the database.
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since 2.3
 */
class GuidType extends StringType
{
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getGuidTypeDeclarationSQL($fieldDeclaration);
    }

    public function getName()
    {
        return Type::GUID;
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
}

Set guid type to require SQL comment hint


<?php

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

class AlterTableIncidentsRenameComponentColumn extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('incidents', function (Blueprint $table) {
            DB::statement("ALTER TABLE `incidents` CHANGE `component` `component_id` TINYINT(4)  NOT NULL  DEFAULT '1'");
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('incidents', function (Blueprint $table) {
            DB::statement("ALTER TABLE `incidents` CHANGE `component_id` `component` TINYINT(4)  NOT NULL  DEFAULT '1'");
        });
    }
}

<?php

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

class AlterTableIncidentsRenameComponentColumn extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('incidents', function (Blueprint $table) {
            $table->rename('component', 'component_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('incidents', function (Blueprint $table) {
            $table->rename('component_id', 'component');
        });
    }
}

Fix renaming of table columns for other database drivers


<?php
	App::uses('CakeEmail', 'Network/Email');

	class FawnoEmail extends CakeEmail {
		protected function _renderTemplates ($content) {
			if (!empty($this->_subject) && empty($this->_viewVars['subject'])) {
				$this->_viewVars['subject'] = $this->_subject;
			}

			$render = parent::_renderTemplates($content);

			if (!empty($render['html'])) {
				if (preg_match_all('~(["\'])cid:([^\1]+)\1~iU', $render['html'], $img)) {
					$img = array_unique($img[2]);
					foreach ($img as $file) if (is_file($file)) {
						$cid = sha1($file);
						$this->_attachments['cid:' . $cid]['data'] = base64_encode(file_get_contents($file));
						$this->_attachments['cid:' . $cid]['contentId'] = $cid;
						$this->_attachments['cid:' . $cid]['mimetype'] = mime_content_type($file);
						$render['html'] = str_replace($file, $cid, $render['html']);
					}
				}
			}

			return $render;
		}
	}
?>

<?php
	App::uses('CakeEmail', 'Network/Email');

	class FawnoEmail extends CakeEmail {
		protected function _renderTemplates ($content) {
			if (!empty($this->_subject) && empty($this->_viewVars['subject'])) {
				$this->_viewVars['subject'] = $this->_subject;
			}

			$render = parent::_renderTemplates($content);

			if (!empty($render['html'])) {
				$render['html'] = str_replace(array('file:', 'file://', 'cid://'), 'cid:', $render['html']);
				if (preg_match_all('~(["\'])cid:([^\1]+)\1~iU', $render['html'], $img)) {
					$img = array_unique($img[2]);
					foreach ($img as $file) if (is_file($file)) {
						$cid = sha1($file);
						$this->_attachments['cid:' . $cid]['data'] = base64_encode(file_get_contents($file));
						$this->_attachments['cid:' . $cid]['contentId'] = $cid;
						$this->_attachments['cid:' . $cid]['mimetype'] = mime_content_type($file);
						$render['html'] = str_replace($file, $cid, $render['html']);
					}
				}
			}

			return $render;
		}
	}
?>

Add cid:// file:// file: schemes

Add cid:// file:// file: schemes

Add cid:// file:// file: schemes, this permits add images with HtmlHelper:
´´´php
echo $this->Html->image('cid://full/path/image');
echo $this->Html->image('file://full/path/image');
´´´


<?php

require_once("/etc/nubis-config/securitywiki.php");

$conn = mysql_connect($DB_SERVER, $DB_USERNAME, $DB_PASSWORD);

if (!$conn) {
    http_response_code(500);
    echo "Can't connect to the database";
    exit;
}

$db = mysql_select_db($DB_NAME);

if (!$db) {
    http_response_code(500);
    echo "Can't find the database $DB_NAME";
    exit;
}

$ping = mysql_ping();

if (!$ping) {
    http_response_code(500);
    echo "Database ping failed";
    exit;
}

echo "All Checks : OK";

?>

<?php

require_once("/etc/nubis-config/securitywiki.php");

$mysqli = new mysqli($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
if (!$mysqli) {
    http_response_code(500);
    echo "Can't connect to the database";
    exit;
}

/* check if server is alive */
if (!$mysqli->ping()) {
    http_response_code(500);
    echo "Database ping failed";
    exit;
}

echo "All Checks : OK";

?>

Use mysqli to not spam logs with deprecation errors


<?php

list($pager, $type) = $s['d'];

?>
<p>
Displaying <?= $pager->getDisplayed() ?> / <?= $pager->getTotal() ?> <?= $type ?>.
</p>

<?php

list($pager, $type) = $s['d'];

?>
<?php if ($pager->getTotal()): ?>
<p>
Displaying <?= $pager->getDisplayed() ?> / <?= $pager->getTotal() ?> <?= $type ?>.
</p>
<?php endif ?>

Hide pager stats without results

Hide pager stats without results

Signed-off-by: Gerco van Heerdt <43740ea33a86c60a8dadd26e55cb69b32c6ef141@gmail.com>


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Payment;

final class PaymentTransitions
{
    public const GRAPH = 'sylius_payment';

    public const TRANSITION_CREATE = 'create';
    public const TRANSITION_PROCESS = 'process';
    public const TRANSITION_COMPLETE = 'complete';
    public const TRANSITION_FAIL = 'fail';
    public const TRANSITION_CANCEL = 'cancel';
    public const TRANSITION_REFUND = 'refund';
    public const TRANSITION_VOID = 'void';

    private function __construct()
    {
    }
}

<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Component\Payment;

final class PaymentTransitions
{
    public const GRAPH = 'sylius_payment';

    public const TRANSITION_CREATE = 'create';
    public const TRANSITION_PROCESS = 'process';
    public const TRANSITION_COMPLETE = 'complete';
    public const TRANSITION_FAIL = 'fail';
    public const TRANSITION_CANCEL = 'cancel';
    public const TRANSITION_AUTHORIZE = 'authorize';
    public const TRANSITION_REFUND = 'refund';
    public const TRANSITION_VOID = 'void';

    private function __construct()
    {
    }
}

Add authorize constant to payment transitions


<?php

namespace li3_quality\tests\cases\test\rules;

class HasCorrectClassNameTest extends \li3_quality\test\Unit {

	public $rule = 'li3_quality\test\rules\HasCorrectClassName';

	public function testWithClosingTag() {
		$code = <<<EOD
namespace bar/baz;
class FooBar {}
EOD;
		$this->assertRulePass(array(
			'source' => $code,
			'path' => '/bar/baz/FooBar.php',
		), $this->rule);
	}

	public function testWithoutClosingTag() {
		$code = <<<EOD
namespace bar/baz;
class foobar {}
EOD;
		$this->assertRuleFail(array(
			'source' => $code,
			'path' => '/bar/baz/foobar.php',
		), $this->rule);
	}

	public function testWithoutMatchingFileName() {
		$code = <<<EOD
namespace bar/baz;
class FooBar {}
EOD;
		$this->assertRuleFail(array(
			'source' => $code,
			'path' => '/bar/baz/foo.php',
		), $this->rule);
	}

}

?>

<?php

namespace li3_quality\tests\cases\test\rules;

class HasCorrectClassNameTest extends \li3_quality\test\Unit {

	public $rule = 'li3_quality\test\rules\HasCorrectClassName';

	public function testWithClosingTag() {
		$code = <<<EOD
namespace bar/baz;
class FooBar {}
EOD;
		$this->assertRulePass(array(
			'source' => $code,
			'path' => '/bar/baz/FooBar.php',
		), $this->rule);
	}

	public function testWithoutClosingTag() {
		$code = <<<EOD
namespace bar/baz;
class foobar {}
EOD;
		$this->assertRuleFail(array(
			'source' => $code,
			'path' => '/bar/baz/foobar.php',
		), $this->rule);
	}

	public function testWithoutMatchingFileName() {
		$code = <<<EOD
namespace bar/baz;
class FooBar {}
EOD;
		$this->assertRuleFail(array(
			'source' => $code,
			'path' => '/bar/baz/foo.php',
		), $this->rule);
	}

	public function testNonPHPFile() {
		$code = <<<EOD
namespace bar/baz;
class FooBar {}
EOD;
		$this->assertRulePass(array(
			'source' => $code,
			'path' => '/bar/baz/foo.txt',
		), $this->rule);
	}

}

?>

Add tests for correct class name which ignores non-php files.

Is this code necessary since we should be ignoring non-php files already?


<?php

// Setup
require_once '../cassowary/cassowary-setup.php';

// logout if necessary

if (phpCAS::isAuthenticated()) {
	phpCAS::logoutWithRedirectService($_SERVER["SCRIPT_URI"]);
}
?>
<!DOCTYPE html>

		<title>Logged Out</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

Logout successful

You have successfully logged out.

Click here to login to <?php echo $_SERVER["HTTP_HOST"] ?> again

For security reasons, exit your web browser.

<?php

// Setup
require_once '../cassowary/cassowary-setup.php';

// logout if necessary

if (phpCAS::isAuthenticated()) {
	phpCAS::logoutWithRedirectService(
		($_SERVER["'HTTPS'"] ? "https://" : "http://" )
		. $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
}
?>
<!DOCTYPE html>

		<title>Logged Out</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

Logout successful

You have successfully logged out.

Click here to login to <?php echo $_SERVER["HTTP_HOST"] ?> again

For security reasons, exit your web browser.

Replace use of SCRIPT_URI for OS X Server compatibility (mod_php environment).


		<?php if ($content_type = Controller::$view->mime_type): ?>
			<?php if (!empty(Controller::$view->charset)) { $content_type .= ';charset=' . Controller::$view->charset; } ?>
			 <meta http-equiv="Content-Type" content="<?php echo $content_type ?>">
		<?php endif; ?>
		<?php if ($author = Backend::getConfig('application.author')): ?>
			<meta name="author" content="<?php echo $author ?>">
		<?php endif; ?>
		<?php if (!empty($meta_description) || $meta_description = Backend::getConfig('application.description')): ?>
			<meta name="description" content="<?php echo $meta_description ?>">
		<?php endif; ?>
		<meta name="generator" content="backend-php.net">
		<?php if (!empty($keywords)): $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords; ?>
			<meta name="keywords" content="<?php echo $keywords ?>">
		<?php endif; ?>
		<?php if (!empty($meta_values) && is_array($meta_values)): ?>
			<?php foreach($meta_values as $name => $value): ?>
				<meta name="<?php echo $name ?>" value="<?php echo $value ?>">
			<?php endforeach; ?>
		<?php endif; ?>

Allow for meta_values in head

Allow for meta_values in head


<?php

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

use Flarum\Extend;
use Flarum\Frontend\Document;
use Psr\Http\Message\ServerRequestInterface as Request;

return [
    (new Extend\Frontend('forum'))
        ->route(
            '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]',
            'embed.discussion',
            function (Document $document, Request $request) {
                // Add the discussion content to the document so that the
                // payload will be included on the page and the JS app will be
                // able to render the discussion immediately.
                app(Flarum\Forum\Content\Discussion::class)($document, $request);

                app(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request);
            }
        ),

    (new Extend\Frontend('embed'))
        ->js(__DIR__.'/js/dist/forum.js')
        ->css(__DIR__.'/less/forum.less')
];

<?php

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

use Flarum\Extend;
use Flarum\Frontend\Document;
use Psr\Http\Message\ServerRequestInterface as Request;

return [
    (new Extend\Frontend('forum'))
        ->route(
            '/embed/{id:\d+(?:-[^/]*)?}[/{near:[^/]*}]',
            'embed.discussion',
            function (Document $document, Request $request) {
                // Add the discussion content to the document so that the
                // payload will be included on the page and the JS app will be
                // able to render the discussion immediately.
                resolve(Flarum\Forum\Content\Discussion::class)($document, $request);

                resolve(Flarum\Frontend\Content\Assets::class)->forFrontend('embed')($document, $request);
            }
        ),

    (new Extend\Frontend('embed'))
        ->js(__DIR__.'/js/dist/forum.js')
        ->css(__DIR__.'/less/forum.less')
];

Use resolve helper instead of app

Use resolve helper instead of app