<?php

namespace Flarum\Tags\Migration;

use Flarum\Database\AbstractMigration;
use Illuminate\Database\Schema\Blueprint;

class MakeSlugUnique extends AbstractMigration
{
    public function up()
    {
        $this->schema->table('tags', function (Blueprint $table) {
            $table->unique('slug');
        });
    }

    public function down()
    {
        $this->schema->table('tags', function (Blueprint $table) {
            $table->dropUnique('tags_slug_unique');
        });
    }
}

<?php

namespace Flarum\Tags\Migration;

use Flarum\Database\AbstractMigration;
use Illuminate\Database\Schema\Blueprint;

class MakeSlugUnique extends AbstractMigration
{
    public function up()
    {
        $this->schema->table('tags', function (Blueprint $table) {
            $table->string('slug', 100)->change();
            $table->unique('slug');
        });
    }

    public function down()
    {
        $this->schema->table('tags', function (Blueprint $table) {
            $table->string('slug', 255)->change();
            $table->dropUnique('tags_slug_unique');
        });
    }
}

Reduce length of slug field to prevent error when creating unique index


<?php

namespace PragmaRX\Sdk\Services\FacebookMessenger\Listeners;

use PragmaRX\Sdk\Services\Chat\Events\EventPublisher;
use PragmaRX\Sdk\Services\Chat\Events\ChatMessageWasSent;
use PragmaRX\Sdk\Services\Chat\Events\ChatMessageWasDelivered;
use PragmaRX\Sdk\Services\FacebookMessenger\Data\Repositories\FacebookMessenger;
use PragmaRX\Sdk\Services\FacebookMessenger\Events\FacebookMessengerAudioWasCreated;

class SendFacebookMessengerMessage
{
    /**
     * @var EventPublisher
     */
    private $eventPublisher;
    /**
     * @var FacebookMessenger
     */
    private $facebookMessengerRepository;

    public function __construct(EventPublisher $eventPublisher, FacebookMessenger $facebookMessengerRepository)
    {
        $this->eventPublisher = $eventPublisher;
        $this->facebookMessengerRepository = $facebookMessengerRepository;
    }

    /**
     * Handle the event.
     *
     * @param FacebookMessengerAudioWasCreated $event
     */
    public function handle(ChatMessageWasSent $event)
    {
        $message = $event->data['message_model'];

        if ($message->chat->facebook_messenger_chat_id)
        {
            if ($this->facebookMessengerRepository->sendMessage($event->data['message_model']))
            {
                event(new ChatMessageWasDelivered($message));
            }
        }

        $this->eventPublisher->publish('ChatListWasUpdated');
    }
}

<?php

namespace PragmaRX\Sdk\Services\FacebookMessenger\Listeners;

use PragmaRX\Sdk\Services\Chat\Events\EventPublisher;
use PragmaRX\Sdk\Services\Chat\Events\ChatMessageWasSent;
use PragmaRX\Sdk\Services\Chat\Events\ChatMessageWasDelivered;
use PragmaRX\Sdk\Services\FacebookMessenger\Data\Repositories\FacebookMessenger;
use PragmaRX\Sdk\Services\FacebookMessenger\Events\FacebookMessengerAudioWasCreated;

class SendFacebookMessengerMessage
{
    /**
     * @var EventPublisher
     */
    private $eventPublisher;
    /**
     * @var FacebookMessenger
     */
    private $facebookMessengerRepository;

    public function __construct(EventPublisher $eventPublisher, FacebookMessenger $facebookMessengerRepository)
    {
        $this->eventPublisher = $eventPublisher;
        $this->facebookMessengerRepository = $facebookMessengerRepository;
    }

    /**
     * Handle the event.
     *
     * @param FacebookMessengerAudioWasCreated $event
     */
    public function handle(ChatMessageWasSent $event)
    {
        $message = $event->data['message_model'];

        if ($message->chat->facebook_messenger_chat_id)
        {
            $this->facebookMessengerRepository->sendMessage($event->data['message_model'])
        }

        $this->eventPublisher->publish('ChatListWasUpdated');
    }
}

Remove message delivery for Facebook

Remove message delivery for Facebook


<?php
namespace wcf\action;
use wcf\system\background\BackgroundQueueHandler;

/**
 * Performs background queue jobs.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2019 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Action
 * @since	3.0
 */
class BackgroundQueuePerformAction extends AbstractAction {
	/**
	 * number of jobs that will be processed per invocation
	 * @var integer
	 */
	public static $jobsPerRun = 5;

	/**
	 * @inheritDoc
	 */
	public function execute() {
		parent::execute();

		header('Content-type: application/json');
		for ($i = 0; $i < self::$jobsPerRun; $i++) {
			if (BackgroundQueueHandler::getInstance()->performNextJob() === false) {
				// there were no more jobs
				break;
			}
		}
		echo BackgroundQueueHandler::getInstance()->getRunnableCount();
		exit;
	}
}

<?php
namespace wcf\action;
use wcf\system\background\BackgroundQueueHandler;
use wcf\system\WCF;

/**
 * Performs background queue jobs.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2019 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\Action
 * @since	3.0
 */
class BackgroundQueuePerformAction extends AbstractAction {
	/**
	 * number of jobs that will be processed per invocation
	 * @var integer
	 */
	public static $jobsPerRun = 5;

	/**
	 * @inheritDoc
	 */
	public function execute() {
		parent::execute();

		header('Content-type: application/json');
		for ($i = 0; $i < self::$jobsPerRun; $i++) {
			if (BackgroundQueueHandler::getInstance()->performNextJob() === false) {
				// there were no more jobs
				break;
			}
		}
		echo BackgroundQueueHandler::getInstance()->getRunnableCount();
		if (WCF::getSession()->isFirstVisit() && !WCF::getUser()->userID) {
			WCF::getSession()->delete();
		}
		exit;
	}
}

Delete firstVisit = true, userID = 0 sessions after processing background queue

These sessions most likely stem from a script / cronjob that is set-up
to regularly request the background queue to ensure it does not fill up
in periods of low user activity. They “fill up” the session table, skew
the user online statistics and are not going to be re-used.


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

abstract class cs_webapplibsAbstract extends cs_versionAbstract {

	protected $gfObj;

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

		if($makeGfObj === true) {
			//make a cs_globalFunctions{} object.
			//TODO::: find a way to avoid h
			require_once(dirname(__FILE__) ."/../../cs-content/cs_globalFunctions.class.php");
			$this->gfObj = new cs_globalFunctions();
		}
    }//end __construct()
	//-------------------------------------------------------------------------
}

?>

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

require_once(dirname(__FILE__) .'/../../cs-content/abstract/cs_version.abstract.class.php');
abstract class cs_webapplibsAbstract extends cs_versionAbstract {

	protected $gfObj;

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

		if($makeGfObj === true) {
			//make a cs_globalFunctions{} object.
			//TODO::: find a way to avoid h
			require_once(dirname(__FILE__) ."/../../cs-content/cs_globalFunctions.class.php");
			$this->gfObj = new cs_globalFunctions();
		}
    }//end __construct()
	//-------------------------------------------------------------------------
}

?>

Fix missing requirement (overwrote in last batch of commits, due to conflicts).


<?php
// Only in Test and Live Environments...
if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) {
  //
  // Disable Core Updates EVERYWHERE (use git upstream)
  //
  add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );

  //
  // Disable Plugin Updates
  //
  add_action('admin_menu','hide_admin_notices');
  function hide_admin_notices() {
    remove_action( 'admin_notices', 'update_nag', 3 );
  }

  remove_action( 'load-update-core.php', 'wp_update_plugins' );
  add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );

  //
  // Disable Theme Updates
  //
  remove_action( 'load-update-core.php', 'wp_update_themes' );
  add_filter( 'pre_site_transient_update_themes', create_function( '$a', "return null;" ) );
}

<?php
// Only in Test and Live Environments...
if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) {
  //
  // Disable Core Updates EVERYWHERE (use git upstream)
  //
  function _pantheon_disable_wp_updates() {
    include ABSPATH . WPINC . '/version.php';
    return (object) array(
	    'updates' => array(),
	    'version_checked' => $wp_version,
	    'last_checked' => time(),
    );
  }

  add_filter( 'pre_site_transient_update_core', '_pantheon_disable_wp_updates' );

  //
  // Disable Plugin Updates
  //
  add_action('admin_menu','hide_admin_notices');
  function hide_admin_notices() {
    remove_action( 'admin_notices', 'update_nag', 3 );
  }

  remove_action( 'load-update-core.php', 'wp_update_plugins' );
  add_filter( 'pre_site_transient_update_plugins', '_pantheon_disable_wp_updates' );

  //
  // Disable Theme Updates
  //
  remove_action( 'load-update-core.php', 'wp_update_themes' );
  add_filter( 'pre_site_transient_update_themes', '_pantheon_disable_wp_updates' );
}

Fix bug with how Pantheon is disabling updates


<?php

namespace wcf\system\database\exception;

/**
 * Denotes an database related error.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Database\Exception
 * @since   3.0
 */
class DatabaseException extends \wcf\system\database\DatabaseException
{
    /** @noinspection PhpMissingParentConstructorInspection */

    /**
     * @inheritDoc
     */
    public function __construct($message, ?\PDOException $previous = null)
    {
        \Exception::__construct($message, 0, $previous);

        // we cannot use the constructor's parameter, because of (http://php.net/manual/en/exception.getcode.php):
        // > Returns the exception code as integer in Exception but possibly as other type in Exception
        // descendants (for example as string in PDOException).
        if ($previous) {
            $this->code = $previous->code;
        }
    }
}

<?php

namespace wcf\system\database\exception;

/**
 * Denotes an database related error.
 *
 * @author  Tim Duesterhus
 * @copyright   2001-2019 WoltLab GmbH
 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package WoltLabSuite\Core\System\Database\Exception
 * @since   3.0
 */
class DatabaseException extends \wcf\system\database\DatabaseException
{
    /** @noinspection PhpMissingParentConstructorInspection */

    /**
     * @inheritDoc
     */
    public function __construct($message, ?\PDOException $previous = null)
    {
        \Exception::__construct($message, 0, $previous);

        // we cannot use the constructor's parameter, because of (http://php.net/manual/en/exception.getcode.php):
        // > Returns the exception code as integer in Exception but possibly as other type in Exception
        // descendants (for example as string in PDOException).
        if ($previous) {
            $this->code = $previous->getCode();
        }
    }
}

Fix PHP 8.1.2 compatibility in DatabaseException

> Cannot access protected property PDOException::$code


<?php

class Benchmark
{
    public function run($runCount = 2500)
    {
        $functions = array("abs", "acos", "asin", "atan", "floor", "exp", "sin", "tan", "sqrt");

        for ($i = 0; $i < $runCount; $i++) {
            foreach ($functions as $function) {
                call_user_func_array($function, array($i));
            }
        }
    }
}

$benchmark = new Benchmark();

$benchmark->run();

<?php

class Benchmark
{
    public function run($runCount = 2500)
    {
        $functions = array("acosh", "asinh", "cos", "log", "log1p", "log10", "sin", "sqrt", "tan");

        for ($i = 0; $i < $runCount; $i++) {
            foreach ($functions as $function) {
                call_user_func_array($function, array($i));
            }
        }
    }
}

$benchmark = new Benchmark();

$benchmark->run();

Improve list of methods use in benchmark


<?php
/**
 * Template for header
 *
 *  section and everything up until

 *
 * @Author: Roni Laukkarinen
 * @Date: 2020-05-11 13:17:32
 * @Last Modified by:   Timi Wahalahti
 * @Last Modified time: 2020-11-19 11:24:53
 *
 * @package air-light
 */

namespace Air_Light;

?>

<!doctype html>
<html <?php language_attributes(); ?>>

  <meta charset="<?php bloginfo( 'charset' ); ?>">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="profile" href="http://gmpg.org/xfn/11">

  <?php wp_head(); ?>

<body <?php body_class( 'no-js' ); ?>>
  <?php wp_body_open(); ?>

    <?php echo esc_html( get_default_localization( 'Skip to content' ) ); ?>

        <?php get_template_part( 'template-parts/header/branding' ); ?>
        <?php get_template_part( 'template-parts/header/navigation' ); ?>

<?php
/**
 * Template for header
 *
 *  section and everything up until

 *
 * @Author: Roni Laukkarinen
 * @Date: 2020-05-11 13:17:32
 * @Last Modified by:   Roni Laukkarinen
 * @Last Modified time: 2021-02-25 13:47:40
 *
 * @package air-light
 */

namespace Air_Light;

?>

<!doctype html>
<html <?php language_attributes(); ?>>

  <meta charset="<?php bloginfo( 'charset' ); ?>">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="profile" href="http://gmpg.org/xfn/11">

  <?php wp_head(); ?>

<body <?php body_class( 'no-js' ); ?>>
  <?php echo esc_html( get_default_localization( 'Skip to content' ) ); ?>

  <?php wp_body_open(); ?>

        <?php get_template_part( 'template-parts/header/branding' ); ?>
        <?php get_template_part( 'template-parts/header/navigation' ); ?>

Move skip link right after body tag

Move skip link right after body tag


<?php

namespace WP_CLI\Bootstrap;

/**
 * Class RegisterDeferredCommands.
 *
 * Registers the deferred commands that for which no parent was registered yet.
 * This is necessary, because we can have sub-commands that have no direct
 * parent, like `wp network meta`.
 *
 * @package WP_CLI\Bootstrap
 */
final class RegisterDeferredCommands implements BootstrapStep {

	/**
	 * Process this single bootstrapping step.
	 *
	 * @param BootstrapState $state Contextual state to pass into the step.
	 *
	 * @return BootstrapState Modified state to pass to the next step.
	 */
	public function process( BootstrapState $state ) {
		$deferred_additions = \WP_CLI::get_deferred_additions();

		foreach ( $deferred_additions as $name => $addition ) {
			\WP_CLI::add_command(
				$name,
				$addition['callable'],
				$addition['args']
			);
		}

		return $state;
	}
}

<?php

namespace WP_CLI\Bootstrap;

/**
 * Class RegisterDeferredCommands.
 *
 * Registers the deferred commands that for which no parent was registered yet.
 * This is necessary, because we can have sub-commands that have no direct
 * parent, like `wp network meta`.
 *
 * @package WP_CLI\Bootstrap
 */
final class RegisterDeferredCommands implements BootstrapStep {

	/**
	 * Process this single bootstrapping step.
	 *
	 * @param BootstrapState $state Contextual state to pass into the step.
	 *
	 * @return BootstrapState Modified state to pass to the next step.
	 */
	public function process( BootstrapState $state ) {
		\WP_CLI::add_hook(
			'after_wp_load',
			array( $this, 'add_deferred_commands' )
		);

		return $state;
	}

	/**
	 * Add deferred commands that are still waiting to be processed.
	 */
	public function add_deferred_commands() {
		$deferred_additions = \WP_CLI::get_deferred_additions();

		foreach ( $deferred_additions as $name => $addition ) {
			\WP_CLI::add_command(
				$name,
				$addition['callable'],
				$addition['args']
			);
		}
	}
}

Move deferred command additions to be processed after `'after_wp_load'` hook.

For the command additions within (mu-)plugins to work, they need to be processed after all plugins have actually been loaded.

Fixes #4122


<?php

namespace SimpleRoute;

final class Route implements RouteInterface
{
    /**
     * @var string[]
     */
    private $methods;

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

    /**
     * @var mixed
     */
    private $handler;

    /**
     * @param string|string[] $method The HTTP method, or an array of, to match
     * @param string $pattern The URI pattern
     * @param mixed $handler The handler
     */
    public function __construct($method, $pattern, $handler)
    {
        if (is_array($method)) {
            $this->methods = $method;
        } else {
            $this->methods = array($method);
        }

        $this->pattern = $pattern;
        $this->handler = $handler;
    }

    /**
     * {@inheritdoc}
     */
    public function getMethods()
    {
        return $this->methods;
    }

    /**
     * {@inheritdoc}
     */
    public function getPattern()
    {
        return $this->pattern;
    }

    /**
     * {@inheritdoc}
     */
    public function getHandler()
    {
        return $this->handler;
    }
}

<?php

namespace SimpleRoute;

final class Route implements RouteInterface
{
    /**
     * @var array
     */
    private static $availableMethods = [
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'HEAD',
    ];

    /**
     * @var string[]
     */
    private $methods;

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

    /**
     * @var mixed
     */
    private $handler;

    /**
     * @param string|string[] $method The HTTP method, or an array of, to match
     * @param string $pattern The URI pattern
     * @param mixed $handler The handler
     */
    public function __construct($method, $pattern, $handler)
    {
        if (is_array($method)) {
            $this->methods = $method;
        } else {
            $this->methods = array($method);
        }

        $this->pattern = $pattern;
        $this->handler = $handler;
    }

    /**
     * {@inheritdoc}
     */
    public function getMethods()
    {
        return $this->methods;
    }

    /**
     * {@inheritdoc}
     */
    public function getPattern()
    {
        return $this->pattern;
    }

    /**
     * {@inheritdoc}
     */
    public function getHandler()
    {
        return $this->handler;
    }
}

Add initial HTTP methods array

Add initial HTTP methods array


<?php

use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Bex\Behat\Context\TestRunnerContext;

class FeatureContext implements SnippetAcceptingContext
{
    /** @var TestRunnerContext $testRunnerContext */
    private $testRunnerContext;

    /**
     * @BeforeScenario
     */
    public function gatherContexts(BeforeScenarioScope $scope)
    {
        $environment = $scope->getEnvironment();

        $this->testRunnerContext = $environment->getContext('Bex\Behat\Context\TestRunnerContext');
    }

    /**
     * @Given I should see the message :message
     */
    public function iShouldSeeTheMessage($message)
    {
        $output = $this->testRunnerContext->getStandardOutputMessage() .
            $this->testRunnerContext->getStandardErrorMessage();

        $this->assertOutputContainsMessage($output, $message);
    }

    /**
     * @param $message
     */
    private function assertOutputContainsMessage($output, $message)
    {
        if (mb_strpos($output, $message) === false) {
            throw new RuntimeException('Behat output did not contain the given message.');
        }
    }
}

<?php

use Behat\Behat\Context\SnippetAcceptingContext;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Bex\Behat\Context\TestRunnerContext;

class FeatureContext implements SnippetAcceptingContext
{
    /** @var TestRunnerContext $testRunnerContext */
    private $testRunnerContext;

    /**
     * @BeforeScenario
     */
    public function gatherContexts(BeforeScenarioScope $scope)
    {
        $environment = $scope->getEnvironment();

        $this->testRunnerContext = $environment->getContext('Bex\Behat\Context\TestRunnerContext');
    }

    /**
     * @Given I should see the message :message
     */
    public function iShouldSeeTheMessage($message)
    {
        $output = $this->testRunnerContext->getStandardOutputMessage() .
            $this->testRunnerContext->getStandardErrorMessage();

        $this->assertOutputContainsMessage($output, $message);
    }

    /**
     * @param $message
     */
    private function assertOutputContainsMessage($output, $message)
    {
        if (mb_strpos($output, $message) === false) {
            throw new RuntimeException('Behat output did not contain the given message. Output: ' . PHP_EOL . $output);
        }
    }
}

Add debug to behat feature

Add debug to behat feature


<?php
namespace Companies20Module;

/**
 * Base class for all companies20 module presenters.
 *
 * @author     Michal Špaček
 * @package    michalspacek.cz
 */
abstract class BasePresenter extends \Nette\Application\UI\Presenter
{

	protected function startup()
	{
		parent::startup();

		$startup = $this->getContext()->getByType(\MichalSpacekCz\Startup::class);
		$startup->startup();
	}

	protected function createTemplate($class = null)
	{
		$helpers = $this->getContext()->getByType(\MichalSpacekCz\Templating\Helpers::class);

		$template = parent::createTemplate($class);
		$template->getLatte()->addFilter(null, [$helpers, 'loader']);
		return $template;
	}

}

<?php
namespace Companies20Module;

/**
 * Base class for all companies20 module presenters.
 *
 * @author     Michal Špaček
 * @package    michalspacek.cz
 */
abstract class BasePresenter extends \Nette\Application\UI\Presenter
{

	protected function createTemplate($class = null)
	{
		$helpers = $this->getContext()->getByType(\MichalSpacekCz\Templating\Helpers::class);

		$template = parent::createTemplate($class);
		$template->getLatte()->addFilter(null, [$helpers, 'loader']);
		return $template;
	}

}

Send security headers in bootstrap and not in presenter so that we have them sent when redirecting from HTTP to HTTPS as well


<?php

namespace Oro\src\Oro\Bundle\EmailBundle\Tests\Unit\Fixtures\Entity;

use Oro\Bundle\AttachmentBundle\Entity\Attachment as BaseAttachment;

class Attachment extends BaseAttachment
{
    protected $supportTarget = true;

    public function setSupportTarget($supportTarget)
    {
        $this->supportTarget = $supportTarget;
    }

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

<?php

namespace Oro\src\Oro\Bundle\EmailBundle\Tests\Unit\Fixtures\Entity;

use Oro\Bundle\AttachmentBundle\Entity\Attachment as BaseAttachment;

class Attachment extends BaseAttachment
{
    protected $supportTarget = true;

    /**
     * @param $supportTarget
     */
    public function setSupportTarget($supportTarget)
    {
        $this->supportTarget = $supportTarget;
    }

    /**
     * @param string $targetClass
     *
     * @return bool
     */
    public function supportTarget($targetClass)
    {
        return $this->supportTarget;
    }
}

CRM-2906: Save attachment as attachment entity
- Support target method


<?php

namespace Oro\Bundle\FormBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ClientValidationExtension extends AbstractTypeExtension
{
    /**
     * Add the image_path option
     *
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setOptional(array('client_validation'));
    }

    /**
     * Pass the client validation flag to the view
     *
     * @param FormView      $view
     * @param FormInterface $form
     * @param array         $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // set an "image_url" variable that will be available when rendering this field
        $view->vars['client_validation'] = isset($options['client_validation'])
            ? (bool) $options['client_validation']
            : true;
    }

    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType()
    {
        return 'form';
    }
}

<?php

namespace Oro\Bundle\FormBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ClientValidationExtension extends AbstractTypeExtension
{
    /**
     * Add the client_validation option
     *
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setOptional(array('client_validation'));
    }

    /**
     * Pass the client validation flag to the view
     *
     * @param FormView      $view
     * @param FormInterface $form
     * @param array         $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // set an "client_validation" variable that will be available when rendering this field
        $view->vars['client_validation'] = isset($options['client_validation'])
            ? (bool) $options['client_validation']
            : true;
    }

    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType()
    {
        return 'form';
    }
}

BAP-1626: Customize multi-step setup forms
- added "client_validation" form type option (comments fixed)


<?php

/**
 * @package plugins.document
 * @subpackage lib
 */
class KOperationEnginePdfCreatorLinux extends KOperationEnginePdfCreator
{
	// List of supported file types
	protected $SUPPORTED_FILE_TYPES = array(
		'Microsoft Word',
		'Microsoft PowerPoint',
		'Microsoft Excel',
		'OpenDocument Text',
		'PDF document',
		'Rich Text Format data',
	);

	protected function getCmdLine()
	{
        if(isset($this->configFilePath))
		{
			$xml = file_get_contents($this->configFilePath);
			$xml = str_replace(
				array(KDLCmdlinePlaceholders::OutDir,KDLCmdlinePlaceholders::OutFileName),
				array($this->outDir,$this->outFilePath),
				$xml);
			file_put_contents($this->configFilePath, $xml);
        }

		$outDir = dirname($this->outFilePath);
		$command = "HOME=/tmp && lowriter --headless --convert-to pdf $this->inFilePath --outdir $outDir";

		return "$command >> \"{$this->logFilePath}\" 2>&1";
	}

	protected function getKillPopupsPath()
	{
		return NULL;
	}
}

Add linux batch for doc conversion

PLAT-10694: Add linux batch for doc conversion


<?php

namespace App\Console\Commands;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class TestSmtpCredentials extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sonar:test:smtp {email}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test the SMTP credentials from your .env file.';

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $email = $this->argument('email');
        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false)
        {
            $this->error($email . " is not a valid email address.");
            return;
        }

        try {
            Mail::send('emails.test', [], function($m) use ($email) {
                $m->from('donotreply@sonar.software','Sonar Customer Portal');
                $m->to($email, $email)
                    ->subject('Sonar customer portal test email!');
            });

            $this->info("Test email to $email sent.");
        }
        catch (Exception $e)
        {
            $this->error("Test email failed with the following: " . $e->getMessage());
        }
    }
}

<?php

namespace App\Console\Commands;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;

class TestSmtpCredentials extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sonar:test:smtp {email}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test the SMTP credentials from your .env file.';

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $email = $this->argument('email');
        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false)
        {
            $this->error($email . " is not a valid email address.");
            return;
        }

        try {
            Mail::send('emails.test', [], function($m) use ($email) {
                $m->from(Config::get("customer_portal.from_address"),Config::get("customer_portal.from_name"));
                $m->to($email, $email)
                    ->subject('Sonar customer portal test email!');
            });

            $this->info("Test email to $email sent.");
        }
        catch (Exception $e)
        {
            $this->error("Test email failed with the following: " . $e->getMessage());
        }
    }
}

Send the test SMTP message from the configured from address/name


<?php
/***************************************************************************
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @category         PH7 Template Engine
 * @package          PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          CC-BY License - http://creativecommons.org/licenses/by/3.0/
 ***************************************************************************/

namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;

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

abstract class Syntax
{
    /** @var string */
    protected $sCode;

    /**
     * Parse pH7Tpl's language syntax.
     *
     * @return void
     */
    abstract public function parse();

    /**
     * @return string
     */
    public function get()
    {
        return $this->sCode;
    }

    /**
     * @param string $sCode
     */
    public function set($sCode)
    {
        $this->sCode = $sCode;
    }
}

<?php
/***************************************************************************
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @category         PH7 Template Engine
 * @package          PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          CC-BY License - http://creativecommons.org/licenses/by/3.0/
 ***************************************************************************/

namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;

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

abstract class Syntax
{
    /** @var string */
    protected $sCode;

    /**
     * Parse pH7Tpl's language syntax.
     *
     * @return void
     */
    abstract public function parse();

    /**
     * Get the converted PHP code from template engine's syntax.
     *
     * @return string
     */
    public function get()
    {
        return $this->sCode;
    }

    /**
     * Set the template contents.
     *
     * @param string $sCode
     */
    public function set($sCode)
    {
        $this->sCode = $sCode;
    }
}

Add (helpful) comments to docBlocks

Add (helpful) comments to docBlocks


<?php

namespace App\Jobs;

use App\Jobs\Job;
use Request;
use Illuminate\Contracts\Bus\SelfHandling;

class SetLocale extends Job implements SelfHandling
{
    /**
     * The availables languages.
     *
     * @array $languages
     */
    protected $languages = ['en','fr'];

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        if(!session()->has('locale'))
        {
            session()->put('locale', Request::getPreferredLanguage($this->languages));
        }

        app()->setLocale(session('locale'));
    }
}

<?php

namespace App\Jobs;

use App\Jobs\Job;
use Request;
use Illuminate\Contracts\Bus\SelfHandling;

class SetLocale extends Job implements SelfHandling
{
    /**
     * The availables languages.
     *
     * @array $languages
     */
    protected $languages;

	public function __construct(){
		$this->languages = config('app.languages');
	}

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {

        if(!session()->has('locale'))
        {
            session()->put('locale', Request::getPreferredLanguage($this->languages));
        }

        app()->setLocale(session('locale'));
    }
}

ADD support to multiple languages from config/app.php config file


<?php get_header(); ?>

    <?php if (!is_front_page()) : ?>

<?php single_post_title(); ?>

    <?php endif; ?>

            <?php
            if (have_posts()) :
                /* Start the Loop */
                while (have_posts()) :
                    the_post();

                /*
                 * Include the Post-Format-specific template for the content.
                 * If you want to override this in a child theme, then include a file
                 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                 */
                endwhile;

            else :
            endif;
            ?>

    <?php get_sidebar(); ?>

<?php
get_footer();

<?php get_header(); ?>

    <?php // get_template_part(SNIPPETS_DIR . '/header/page', 'header'); ?>

            <?php
            if (have_posts()) :
                /* Start the Loop */
                while (have_posts()) :
                    the_post();

                    /*
                     * Include the Post-Format-specific template for the content.
                     * If you want to override this in a child theme, then include a file
                     * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                     */
                    get_template_part(SNIPPETS_DIR . '/content/content');
                endwhile;

            else :
                get_template_part(SNIPPETS_DIR . '/content/content', 'none');
            endif;
            ?>

    <?php get_sidebar(); ?>

<?php
get_footer();

Replace code blocks with snippets

Replace code blocks with snippets


<?php

namespace Roots\Sage\Extras;

use Roots\Sage\Config;

/**
 * Add  classes
 */
function body_class($classes) {
  // Add page slug if it doesn't exist
  if (is_single() || is_page() && !is_front_page()) {
    if (!in_array(basename(get_permalink()), $classes)) {
      $classes[] = basename(get_permalink());
    }
  }

  // Add class if sidebar is active
  if (Config\display_sidebar()) {
    $classes[] = 'sidebar-primary';
  }

  return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');

/**
 * Clean up the_excerpt()
 */
function excerpt_more() {
  return ' … ' . __('Continued', 'sage') . '';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');

// stop WordPress from adding p tags to things
remove_filter ('the_content',  'wpautop');
remove_filter ('comment_text', 'wpautop');

Revert "Added filters to stop WordPress from automatically adding p tags"

This reverts commit 28770297b88c997c8ec9e7952eeb88e77248f7d3.


<?php

namespace OParl\Website\Api\Controllers;

use function Swagger\scan;

/**
 * @SWG\Swagger(
 *     schemes={"https"},
 *     host="dev.oparl.org",
 *     basePath="/api/",
 *     @SWG\Info(
 *         title="OParl Developer Platform API",
 *         description="Meta information concerning the OParl ecosystem",
 *         version="0",
 *         @SWG\License(
 *             name="CC-4.0-BY",
 *             url="https://creativecommons.org/licenses/by/4.0/"
 *         )
 *     ),
 *     produces={ "application/json" }
 * )
 */
class ApiController
{
    /**
     * Return the dynamically updated swagger.json for the meta endpoints.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function swaggerJson()
    {
        $swagger = scan(base_path('lib/Api/Controllers'));

        return response($swagger, 200, [
            'Content-Tyype'               => 'application/json',
            'Access-Control-Allow-Origin' => '*',
        ]);
    }

    /**
     * Index page for the api.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        return view('api.index');
    }
}

<?php

namespace OParl\Website\Api\Controllers;

use function Swagger\scan;

/**
 * @SWG\Swagger(
 *     schemes={"https"},
 *     host="dev.oparl.org",
 *     basePath="/api/",
 *     @SWG\Info(
 *         title="OParl Developer Platform API",
 *         description="Meta information concerning the OParl ecosystem",
 *         version="0",
 *         @SWG\License(
 *             name="CC-4.0-BY",
 *             url="https://creativecommons.org/licenses/by/4.0/"
 *         )
 *     ),
 *     produces={ "application/json" }
 * )
 */
class ApiController
{
    /**
     * Return the dynamically updated swagger.json for the meta endpoints.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function swaggerJson()
    {
        $swagger = scan(base_path('lib/Api/Controllers'));

        return response($swagger, 200, [
            'Content-Type'               => 'application/json',
            'Access-Control-Allow-Origin' => '*',
        ]);
    }

    /**
     * Index page for the api.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        return view('api.index');
    }
}

Fix typo in content type

Fix typo in content type


<?
if (is_object($configuration)) {
	$path = $configuration->getRootPath();
	$relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path)?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath)?>

<?php
defined('C5_EXECUTE') or die('Access Denied');
if (is_object($configuration)) {
	$path = $configuration->getRootPath();
	$relativePath = $configuration->getWebRootRelativePath();
}
?>
<? $form = Loader::helper('form'); ?>

    <?=t('Root Path')?>

        <?=$form->text('fslType[path]', $path)?>

    <?=t('Relative Path')?>
    <?=$form->text('fslType[relativePath]', $relativePath)?>

Add a c5_execute or die

Add a c5_execute or die

Former-commit-id: 1ab7033f04df48da857139fd1bbf7cf8788ddfb4


<?php  namespace Rossedman\Teamwork;

use Rossedman\Teamwork\Traits\RestfulTrait;

class Time extends AbstractObject {

    use RestfulTrait;

    protected $wrapper  = 'time-entry';

    protected $endpoint = 'time_entries';

    /**
     * GET /time.json
     *
     * @return mixed
     */
    public function all($args = null)
    {
        $this->areArgumentsValid($args, ['page']);

        return $this->client->get($this->endpoint, $args)->response();
    }
}

<?php  namespace Rossedman\Teamwork;

use Rossedman\Teamwork\Traits\RestfulTrait;

class Time extends AbstractObject {

    use RestfulTrait;

    protected $wrapper  = 'time-entry';

    protected $endpoint = 'time_entries';

    /**
     * GET /time_entries.json
     *
     * @return mixed
     */
    public function all($args = null)
    {
        $this->areArgumentsValid($args, ['page']);

        return $this->client->get($this->endpoint, $args)->response();
    }
}

Correct the URI in the comment for the all() function


<?php
include( '../config.php' );

$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;

$data = file_get_contents( $url );

$shows = new SimpleXMLElement( $data );

$items = array();

foreach( $shows->channel->item as $show ):
    preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
    $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );

    if( !isset( $items[ $dateString ] ) ):
        $items[ $dateString ] = array();
    endif;

    $item = array();

    $item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );

    $items[ $dateString ][] = $item;
endforeach;

header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );

<?php
include( '../config.php' );

$url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes;

$data = file_get_contents( $url );

$shows = new SimpleXMLElement( $data );

$items = array();

foreach( $shows->channel->item as $show ):
    preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches );
    $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) );

    if( !isset( $items[ $dateString ] ) ):
        $items[ $dateString ] = array();
    endif;

    $item = array();

    $item[ 'image' ] = $_SERVER[ 'REQUEST_URI' ] . 'images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) );

    $items[ $dateString ][] = $item;
endforeach;

header( 'Access-Control-Allow-Origin: *' );
header( 'Content-Type: application/json' );
echo json_encode( $items );

Make the image path work even if it's in a subfolder


<?php
/**
 * Created by PhpStorm.
 * User: quimmanrique
 * Date: 13/02/17
 * Time: 19:13
 */

namespace Cmp\Queues\Infrastructure\AmqpLib\v26\RabbitMQ\Queue;

use Cmp\Queues\Domain\Queue\JSONMessageFactory;
use PhpAmqpLib\Message\AMQPMessage;
use Psr\Log\LoggerInterface;

class MessageHandler
{
    /**
     * @var JSONMessageFactory
     */
    private $jsonMessageFactory;

    /**
     * @var callable
     */
    private $callback;

    /**
     * MessageHandler constructor.
     * @param JSONMessageFactory $jsonMessageFactory
     */
    public function __construct(JSONMessageFactory $jsonMessageFactory)
    {
        $this->jsonMessageFactory = $jsonMessageFactory;
    }

    /**
     * @param AMQPMessage $message
     * @throws \Exception
     */
    public function handleMessage(AMQPMessage $message)
    {
        try {
            $task = $this->jsonMessageFactory->create($message->body);
            call_user_func_array($this->callback, [$task]);
            $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function setCallback(callable $callback)
    {
        $this->callback = $callback;
    }
}

<?php
namespace Cmp\Queues\Infrastructure\AmqpLib\v26\RabbitMQ\Queue;

use Cmp\Queues\Domain\Queue\JSONMessageFactory;
use PhpAmqpLib\Message\AMQPMessage;

class MessageHandler
{
    /**
     * @var JSONMessageFactory
     */
    private $jsonMessageFactory;

    /**
     * @var callable
     */
    private $callback;

    /**
     * MessageHandler constructor.
     * @param JSONMessageFactory $jsonMessageFactory
     */
    public function __construct(JSONMessageFactory $jsonMessageFactory)
    {
        $this->jsonMessageFactory = $jsonMessageFactory;
    }

    /**
     * @param AMQPMessage $message
     * @throws \Exception
     */
    public function handleMessage(AMQPMessage $message)
    {
        $task = $this->jsonMessageFactory->create($message->body);
        call_user_func_array($this->callback, [$task]);
        $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
    }

    public function setCallback(callable $callback)
    {
        $this->callback = $callback;
    }
}

Remove useless try catch block

Remove useless try catch block


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use Listabierta\Bundle\MunicipalesBundle\Form\Type\CandidacyStep1Type;

class CandidacyController extends Controller
{
    public function indexAction(Request $request)
    {
        $this->step1Action();
    }

    public function step1Action(Request $request)
    {
    	$form = $this->createForm(new CandidacyStep1Type());

    	$form->handleRequest($request);

    	if ($form->isValid())
    	{

    	}

    	return $this->render('MunicipalesBundle:Candidacy:step1.html.twig', array('form' => $form->createView()));
    }
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

use Listabierta\Bundle\MunicipalesBundle\Form\Type\CandidacyStep1Type;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\CandidacyStep2Type;

class CandidacyController extends Controller
{
    public function indexAction(Request $request)
    {
        $this->step1Action();
    }

    public function step1Action(Request $request)
    {
    	$form = $this->createForm(new CandidacyStep1Type(), NULL, array(
    			'action' => $this->generateUrl('municipales_candidacy_step1'),
			    'method' => 'POST',
    			)
    	);

    	$form->handleRequest($request);

    	if ($form->isValid())
    	{
    		$warnings = array();

    		$form2 = $this->createForm(new CandidacyStep2Type(), NULL, array(
    				'action' => $this->generateUrl('municipales_candidacy_step2'),
    				'method' => 'POST',
    		));

    		$form2->handleRequest($request);

    		return $this->render('MunicipalesBundle:Candidacy:step2.html.twig', array(
    				'warnings' => $warnings,
    				'errors' => $form->getErrors(),
    				'form' => $form2->createView()
    			)
    		);
    	}

    	return $this->render('MunicipalesBundle:Candidacy:step1.html.twig', array(
    			'form' => $form->createView(),
    			'errors' => $form->getErrors(),
    	));
    }
}

Implement form for step 2

Implement form for step 2


<?php
function graph_slurm_probejob_pendtime ( &$rrdtool_graph ) {
	global $rrd_dir;

	$series =
		  "DEF:'general'='${rrd_dir}/slurmmond_probejob_pendtime_general.rrd':'sum':AVERAGE "
		. "DEF:'interact'='${rrd_dir}/slurmmond_probejob_pendtime_interact.rrd':'sum':AVERAGE "
		. "LINE2:'general'#0000ff:'general' "
		. "LINE2:'interact'#00ff00:'interact' "
		;

	//required
	$rrdtool_graph['title'] = '-- Slurm Time Probe Jobs Spent Pending --';
	$rrdtool_graph['vertical-label'] = 'seconds';
	$rrdtool_graph['series'] = $series;

	return $rrdtool_graph;
}
?>

<?php

function graph_slurm_probejob_pendtime ( &$rrdtool_graph ) {
        global $rrd_dir;

        $config = file_get_contents("/etc/slurmmon.conf");
        $json_conf= json_decode($config,true);

        $series="";
        foreach ( $json_conf['probejob_partitions'] as $partition)
        {
                $series =  $series."DEF:'".$partition."'='${rrd_dir}/slurmmond_probejob_pendtime_".$partition.".rrd':'sum':AVERAGE ";

        }

        $colours=array("#00000f","#FF0000","#00FF00","#FFFF00","#0000FF");
        $i=0;
        foreach ( $json_conf['probejob_partitions'] as $partition)
        {
                $series =  $series."LINE2:'".$partition."'".$colours[$i].":'".$partition."' ";
                $i++;

        }

        //required
        $rrdtool_graph['title'] = '-- Slurm Time Probe Jobs Spent Pending --';
        $rrdtool_graph['vertical-label'] = 'seconds';
        $rrdtool_graph['series'] = $series;

        //      return $rrdtool_graph;
}
?>

Read partition names from configuration file rather than use hardcoded partition names


<?php
require '../src/Curl/Curl.php';

use \Curl\Curl;

$curl = new Curl();
$curl->get('https://domainr.com/api/json/search', array(
    'client_id' => 'php_curl_class',
    'q' => 'example',
));

foreach ($curl->response->results as $result) {
    echo $result->domain . ' is ' . $result->availability . '.' . "\n";
}

<?php
require '../src/Curl/Curl.php';

use \Curl\Curl;

$curl = new Curl();
$curl->get('https://api/domainr.com/v1/search', array(
    'client_id' => 'php_curl_class',
    'q' => 'example',
));

foreach ($curl->response->results as $result) {
    echo $result->domain . ' is ' . $result->availability . '.' . "\n";
}

Update to new v1 endpoint

Update to new v1 endpoint

We're moving to a versioned API endpoint. Thanks!


<?php

namespace Oro\Bundle\TranslationBundle\Handler;

use Oro\Bundle\ImportExportBundle\Handler\ExportHandler;

use Oro\Bundle\TranslationBundle\Entity\Language;

class TranslationExportHandler extends ExportHandler
{
    protected $language;

    /**
     * {@inheritdoc}
     */
    protected function generateExportFileName($prefix, $extension)
    {
        if (($this->language instanceof Language) && ($this->language->getCode())) {
            return parent::generateExportFileName('translations--' . $this->language->getCode() . '--', $extension);
        }

        return parent::generateExportFileName($prefix, $extension);
    }

    /**
     * @param Language $language
     *
     * @return $this
     */
    public function setLanguage(Language $language)
    {
        $this->language = $language;

        return $this;
    }
}

<?php

namespace Oro\Bundle\TranslationBundle\Handler;

use Oro\Bundle\ImportExportBundle\Handler\ExportHandler;

use Oro\Bundle\TranslationBundle\Entity\Language;

class TranslationExportHandler extends ExportHandler
{
    /**
     * @var Language
     */
    protected $language;

    /**
     * {@inheritdoc}
     */
    protected function generateExportFileName($prefix, $extension)
    {
        if (($this->language instanceof Language) && ($this->language->getCode())) {
            return parent::generateExportFileName('translations--' . $this->language->getCode() . '--', $extension);
        }

        return parent::generateExportFileName($prefix, $extension);
    }

    /**
     * @param Language $language
     *
     * @return $this
     */
    public function setLanguage(Language $language)
    {
        $this->language = $language;

        return $this;
    }
}

BAP-11419: Implement Download (Export) functionality
- Fixed missed typehint


  <?php
    wp_footer();

    if (is_single() && in_category('Articles')) {
  ?>

  <?php
    }

  ?>

Remove unneeded jquery script include

Remove unneeded jquery script include


<?php namespace NZTim\Queue\Commands;

use Illuminate\Console\Command;
use NZTim\Queue\QueueManager;

class ListCommand extends Command
{
    protected $signature = 'queuemgr:list {days=7}';

    protected $description = 'Lists recent jobs within the specified number of days';

    /** @var QueueManager */
    protected $queueManager;

    public function __construct(QueueManager $queueManager)
    {
        parent::__construct();
        $this->queueManager = $queueManager;
    }

    public function handle()
    {
        $days = $this->argument('days');
        $entries = $this->queueManager->recent($days);
        foreach($entries as $entry) {
            $message = $entry->created_at->format('Y-m-d @ H:i') . ' | ';
            $message .= "ID:{$entry->getId()} | ";
            $message .= get_class($entry->getJob()) . ' | ';
            $status = "Complete";
            $method = "info";
            if (is_null($entry->deleted_at)) {
                $status = "Incomplete";
                $method = "error";
            }
            $status .= " ({$entry->attempts})";
            if ($entry->attempts == 0) {
                $status = "Failed!";
                $method = 'error';
            }
            $message .= $status;
            $this->$method($message);
        }
    }
}

<?php namespace NZTim\Queue\Commands;

use Illuminate\Console\Command;
use NZTim\Queue\QueuedJob\QueuedJob;
use NZTim\Queue\QueueManager;

class ListCommand extends Command
{
    protected $signature = 'queuemgr:list {days=7}';

    protected $description = 'Lists recent jobs within the specified number of days';

    /** @var QueueManager */
    protected $queueManager;

    public function __construct(QueueManager $queueManager)
    {
        parent::__construct();
        $this->queueManager = $queueManager;
    }

    public function handle()
    {
        $days = $this->argument('days');
        $entries = $this->queueManager->recent($days);
        $jobs = [];
        foreach($entries as $entry) {
            /** @var QueuedJob $entry */
            $job['Created'] = $entry->created_at->format('Y-m-d - H:i');
            $job['ID'] =  "ID:{$entry->getId()}";
            $job['Class'] = get_class($entry->getJob());
            $job['Status'] = is_null($entry->deleted_at) ? "Incomplete" : "Complete";
            $job['Status'] .= " ({$entry->attempts})";
            if ($entry->attempts == 0) {
                $job['Status'] = "Failed!!!";
            }
            $jobs[] = $job;
        }
        if (count($jobs)) {
            $this->table(array_keys($jobs[0]), $jobs);
        } else {
            $this->info('No jobs found');
        }
    }
}

Update list command to display table

Update list command to display table


<?php

namespace ZpgRtf\Methods;

use League\JsonGuard\Validator;
use League\JsonReference\Dereferencer;
use ZpgRtf\Objects\BranchObject;

/**
 * The branch method allows you to update a branch.
 */
class BranchMethod extends AbstractMethod
{
    /** @var string */
    const UPDATE_SCHEMA = 'http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/branch/update.json';

    /** @var string */
    const UPDATE_URI = 'branch/update';

    /**
     * @return bool
     *
     * @throws \Exception If validation fails. Needs a custom exception type.
     */
    public function update(BranchObject $branchObject)
    {
        $payload = json_encode($branchObject);
        $schema = Dereferencer::draft4()->dereference(self::UPDATE_SCHEMA);
        $validator = new Validator(json_decode($payload), $schema);

        if ($validator->fails()) {
            throw new \Exception('Fails validation');
        }

        $result = $this->getClient()->request('POST', self::UPDATE_URI, [
            'body' => $payload
        ]);

        return $result;
    }
}

<?php

namespace ZpgRtf\Methods;

use League\JsonGuard\Validator;
use League\JsonReference\Dereferencer;
use ZpgRtf\Objects\BranchObject;

/**
 * The branch method allows you to update a branch.
 */
class BranchMethod extends AbstractMethod
{
    /** @var string */
    const UPDATE_SCHEMA = 'http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/branch/update.json';

    /**
     * @return \GuzzleHttp\Psr7\Response
     */
    public function update(BranchObject $branchObject)
    {
        return $this->validateAndSend(self::UPDATE_SCHEMA, 'branch/update', $branchObject);
    }
}

Update branch method for new abstracted validate and send logic


<?php

namespace ItvisionSy\LaravelExtras\Presenter;

use ArrayIterator as Iterator;
use Illuminate\Database\Eloquent\Collection as ECollection;

/**
 * Description of PresenterCollection
 *
 * @author muhannad
 */
class Collection extends ECollection {

    protected $presenter = false;

    public function presenter($set = null) {
        if ($set === null) {
            return $this->presenter;
        } else {
            $this->presenter = !!$set;
        }
    }

    public function getIterator() {
        if ($this->presenter) {
            return new ArrayIterator($this->items);
        } else {
            return new Iterator($this->items);
        }
    }

    public function paginator(\Illuminate\Pagination\Paginator &$paginator) {
        $items = [];
        foreach ($this as $item) {
            $items[] = $item;
        }
        $paginator->setItems($items);
        return $paginator;
    }

}

<?php

namespace ItvisionSy\LaravelExtras\Presenter;

use ArrayIterator as Iterator;
use Illuminate\Database\Eloquent\Collection as ECollection;

/**
 * Description of PresenterCollection
 *
 * @author muhannad
 */
class Collection extends ECollection {

    protected $presenter = false;

    public function presenter($set = null) {
        if ($set === null) {
            return $this->presenter;
        } else {
            $this->presenter = !!$set;
            return $this;
        }
    }

    public function getIterator() {
        if ($this->presenter) {
            return new ArrayIterator($this->items);
        } else {
            return new Iterator($this->items);
        }
    }

    public function paginate(\Illuminate\Database\Eloquent\Builder $query, $size = null) {
        $paginator = $query->paginate($size);
        $this->paginator($paginator);
        return $paginator;
    }

    public function paginator(\Illuminate\Pagination\Paginator &$paginator) {
        $items = [];
        foreach ($this as $item) {
            $items[] = $item;
        }
        $paginator->setItems($items);
        return $paginator;
    }

}

Allow pagination from query Fluid presenter method


<?php

/*
 * This file is part of the YDD\Vebra package.
 *
 * (c) 2012 Damon Jones <damon@yummyduckdesign.co.uk> and Matthew Davis <matt@yummyduckdesign.co.uk>

 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace YDD\Vebra\Model;

/**
 * ChangedPropertySummary
 */
class ChangedPropertySummary extends PropertySummary
{
    protected $lastAction;

    /**
     * set LastAction
     *
     * @param string $lastAction
     *
     * @return object
     */
    public function setLastAction($lastAction)
    {
        $this->lastAction = $lastAction;

        return $this;
    }

    /**
     * get LastAction
     *
     * @return string
     */
    public function getLastAction()
    {
        return $this->lastAction;
    }

     /**
     * get ClientId
     *
     * @return int $clientId
     */
    public function getClientId()
    {
        preg_match('#branch\/(\d+)/#', $this->url, $matches);

        return isset($matches[1]) ? (int) $matches[1] : null;
    }
}

<?php

/*
 * This file is part of the YDD\Vebra package.
 *
 * (c) 2012 Damon Jones <damon@yummyduckdesign.co.uk> and Matthew Davis <matt@yummyduckdesign.co.uk>

 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace YDD\Vebra\Model;

/**
 * ChangedPropertySummary
 */
class ChangedPropertySummary extends PropertySummary
{
    protected $lastAction;

    /**
     * set LastAction
     *
     * @param string $lastAction
     *
     * @return object
     */
    public function setLastAction($lastAction)
    {
        $this->lastAction = $lastAction;

        return $this;
    }

    /**
     * get LastAction
     *
     * @return string
     */
    public function getLastAction()
    {
        return $this->lastAction;
    }
}

Remove the files Matt re-added

Remove the files Matt re-added

This reverts commit 18106dac8014cd215ba01ac416bccd3bdebc6fa9.


<?php

final class PhabricatorRepositoryArcanistProject
  extends PhabricatorRepositoryDAO {

  protected $name;
  protected $phid;
  protected $repositoryID;

  protected $symbolIndexLanguages = array();
  protected $symbolIndexProjects  = array();

  public function getConfiguration() {
    return array(
      self::CONFIG_AUX_PHID   => true,
      self::CONFIG_TIMESTAMPS => false,
      self::CONFIG_SERIALIZATION => array(
        'symbolIndexLanguages' => self::SERIALIZATION_JSON,
        'symbolIndexProjects'  => self::SERIALIZATION_JSON,
      ),
    ) + parent::getConfiguration();
  }

  public function generatePHID() {
    return PhabricatorPHID::generateNewPHID('APRJ');
  }

  public function loadRepository() {
    if (!$this->getRepositoryID()) {
      return null;
    }
    return id(new PhabricatorRepository())->load($this->getRepositoryID());
  }

  public function delete() {
    $this->openTransaction();
      $conn_w = $this->establishConnection('w');

      $symbols = id(new PhabricatorRepositorySymbol())->loadAllWhere(
        'arcanistProjectID = %d',
        $this->getID()
      );
      foreach ($symbols as $symbol) {
        $symbol->delete();
      }

      $result = parent::delete();
    $this->saveTransaction();
    return $result;
  }

}

<?php

final class PhabricatorRepositoryArcanistProject
  extends PhabricatorRepositoryDAO {

  protected $name;
  protected $phid;
  protected $repositoryID;

  protected $symbolIndexLanguages = array();
  protected $symbolIndexProjects  = array();

  public function getConfiguration() {
    return array(
      self::CONFIG_AUX_PHID   => true,
      self::CONFIG_TIMESTAMPS => false,
      self::CONFIG_SERIALIZATION => array(
        'symbolIndexLanguages' => self::SERIALIZATION_JSON,
        'symbolIndexProjects'  => self::SERIALIZATION_JSON,
      ),
    ) + parent::getConfiguration();
  }

  public function generatePHID() {
    return PhabricatorPHID::generateNewPHID('APRJ');
  }

  public function loadRepository() {
    if (!$this->getRepositoryID()) {
      return null;
    }
    return id(new PhabricatorRepository())->load($this->getRepositoryID());
  }

  public function delete() {
    $this->openTransaction();

      queryfx(
        $this->establishConnection('w'),
        'DELETE FROM %T WHERE arcanistProjectID = %d',
        id(new PhabricatorRepositorySymbol())->getTableName(),
        $this->getID());

      $result = parent::delete();
    $this->saveTransaction();
    return $result;
  }

}

Clean up repositories with symbols correctly

Summary: We currently try to delete symbols by ID, but the table has a multipart primary key and no `id` column.

Test Plan: Ran query locally; had @JThramer verify fix in his environment.

Reviewers: btrahan

Reviewed By: btrahan

CC: JThramer, aran

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


<?php

namespace RMiller\PhpSpecExtension;

use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface;
use Behat\Testwork\ServiceContainer\ExtensionManager;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

class PhpSpecExtension implements ExtensionInterface
{

    /**
     * {@inheritDoc}
     */
    public function load(ContainerBuilder $container, array $config)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__));
        $loader->load('services.xml');

        $container->setParameter('phpspec_extension.path', $config['path']);
        $container->setParameter('phpspec_extension.config', $config['config']);
    }

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

    /**
     * {@inheritDoc}
     */
    public function getConfigKey()
    {
        return 'phpspec';
    }

    /**
     * {@inheritdoc}
     */
    public function initialize(ExtensionManager $extensionManager)
    {
    }

    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
    }
}

<?php

namespace RMiller\PhpSpecExtension;

use Behat\Testwork\ServiceContainer\Extension as ExtensionInterface;
use Behat\Testwork\ServiceContainer\ExtensionManager;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

class PhpSpecExtension implements ExtensionInterface
{

    /**
     * {@inheritDoc}
     */
    public function load(ContainerBuilder $container, array $config)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__));
        $loader->load('services.xml');

        $container->setParameter('phpspec_extension.path', $config['path']);
        $container->setParameter('phpspec_extension.config', $config['config']);
    }

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

    /**
     * {@inheritDoc}
     */
    public function getConfigKey()
    {
        return 'phpspec';
    }

    /**
     * {@inheritdoc}
     */
    public function initialize(ExtensionManager $extensionManager)
    {
    }

    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
    }
}

Set default value for path of config

Set default value for path of config


<?php

/*
 * This file is part of the league/commonmark package.
 *
 * (c) Colin O'Dell <colinodell@gmail.com>
 *
 * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
 *  - (c) John MacFarlane
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace League\CommonMark\Inline\Element;

class Image extends AbstractWebResource
{
    /**
     * @var InlineCollection
     */
    protected $altText;

    /**
     * @param string $url
     * @param InlineCollection|string $label
     * @param string $title
     */
    public function __construct($url, $label = null, $title = '')
    {
        parent::__construct($url);

        if (is_string($label)) {
            $this->altText = new InlineCollection(array(new Text($label)));
        } else {
            $this->altText = $label;
        }

        if (!empty($title)) {
            $this->attributes['title'] = $title;
        }
    }

    /**
     * @return InlineCollection
     */
    public function getAltText()
    {
        return $this->altText;
    }

    /**
     * @param InlineCollection $label
     *
     * @return $this
     */
    public function setAltText($label)
    {
        if (is_string($label)) {
            $this->altText = new InlineCollection(array(new Text($label)));
        } else {
            $this->altText = $label;
        }

        return $this;
    }
}

<?php

/*
 * This file is part of the league/commonmark package.
 *
 * (c) Colin O'Dell <colinodell@gmail.com>
 *
 * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
 *  - (c) John MacFarlane
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace League\CommonMark\Inline\Element;

class Image extends AbstractWebResource
{
    /**
     * @var InlineCollection
     */
    protected $altText;

    /**
     * @param string $url
     * @param InlineCollection|string $label
     * @param string $title
     */
    public function __construct($url, $label = null, $title = '')
    {
        parent::__construct($url);

        $this->setAltText($label);

        if (!empty($title)) {
            $this->attributes['title'] = $title;
        }
    }

    /**
     * @return InlineCollection
     */
    public function getAltText()
    {
        return $this->altText;
    }

    /**
     * @param InlineCollection|string $label
     *
     * @return $this
     */
    public function setAltText($label)
    {
        if (is_string($label)) {
            $this->altText = new InlineCollection(array(new Text($label)));
        } else {
            $this->altText = $label;
        }

        return $this;
    }
}

Remove duplicate code; fix docblock

Remove duplicate code; fix docblock


<?php

/*
 * This file is part of the league/commonmark package.
 *
 * (c) Colin O'Dell <colinodell@gmail.com>
 *
 * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
 *  - (c) John MacFarlane
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace League\CommonMark\Inline\Element;

class Image extends AbstractWebResource
{
    /**
     * @var InlineCollection
     */
    protected $altText;

    /**
     * @param string $url
     * @param InlineCollection|string $label
     * @param string $title
     */
    public function __construct($url, $label = null, $title = '')
    {
        parent::__construct($url);

        if (is_string($label)) {
            $this->altText = new InlineCollection(array(new Text($label)));
        } else {
            $this->altText = $label;
        }

        if (!empty($title)) {
            $this->attributes['title'] = $title;
        }
    }

    /**
     * @return InlineCollection
     */
    public function getAltText()
    {
        return $this->altText;
    }

    /**
     * @param InlineCollection $label
     *
     * @return $this
     */
    public function setAltText($label)
    {
        $this->altText = $label;

        return $this;
    }
}

<?php

/*
 * This file is part of the league/commonmark package.
 *
 * (c) Colin O'Dell <colinodell@gmail.com>
 *
 * Original code based on the CommonMark JS reference parser (http://bitly.com/commonmarkjs)
 *  - (c) John MacFarlane
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace League\CommonMark\Inline\Element;

class Image extends AbstractWebResource
{
    /**
     * @var InlineCollection
     */
    protected $altText;

    /**
     * @param string $url
     * @param InlineCollection|string $label
     * @param string $title
     */
    public function __construct($url, $label = null, $title = '')
    {
        parent::__construct($url);

        if (is_string($label)) {
            $this->altText = new InlineCollection(array(new Text($label)));
        } else {
            $this->altText = $label;
        }

        if (!empty($title)) {
            $this->attributes['title'] = $title;
        }
    }

    /**
     * @return InlineCollection
     */
    public function getAltText()
    {
        return $this->altText;
    }

    /**
     * @param InlineCollection $label
     *
     * @return $this
     */
    public function setAltText($label)
    {
        if (is_string($label)) {
            $this->altText = new InlineCollection(array(new Text($label)));
        } else {
            $this->altText = $label;
        }

        return $this;
    }
}

Make it easier to set image alt text

Make it easier to set image alt text


<?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.
 */

namespace Flarum\Mail;

use Flarum\Settings\SettingsRepositoryInterface;
use Swift_Transport;

/**
 * An interface for a mail service.
 *
 * This interface provides all methods necessary for configuring, checking and
 * using one of Laravel's various email drivers throughout Flarum.
 *
 * @public
 */
interface DriverInterface
{
    /**
     * Provide a list of settings for this driver.
     */
    public function availableSettings(): array;

    /**
     * Build a mail transport based on Flarum's current settings.
     */
    public function buildTransport(SettingsRepositoryInterface $settings): Swift_Transport;
}

<?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.
 */

namespace Flarum\Mail;

use Flarum\Settings\SettingsRepositoryInterface;
use Swift_Transport;

/**
 * An interface for a mail service.
 *
 * This interface provides all methods necessary for configuring, checking and
 * using one of Laravel's various email drivers throughout Flarum.
 *
 * @public
 */
interface DriverInterface
{
    /**
     * Provide a list of settings for this driver.
     *
     * The list must be an array of field names (keys) mapping to their type
     * (the empty string "" for a text field; or an array of possible values for
     * a dropdown field).
     */
    public function availableSettings(): array;

    /**
     * Build a mail transport based on Flarum's current settings.
     */
    public function buildTransport(SettingsRepositoryInterface $settings): Swift_Transport;
}

Document changes in mail driver interface


<?php

namespace Rosio\EncryptedCookie;

class CookieFactory
{
	private $cryptoSystem;

	function __construct (iCryptoSystem $cryptoSystem)
	{
		$this->cryptoSystem = $cryptoSystem;
	}

	function createCookie ($name)
	{
		return new EncryptedCookie ($name)->setCryptoSystem($this->cryptoSystem);
	}

	function getCookie ($name)
	{
		return new EncryptedCookie($name)->setCryptoSystem($this->cryptoSystem)->load();
	}
}

<?php

namespace Rosio\EncryptedCookie;

use Rosio\EncryptedCookie\CryptoSystem\iCryptoSystem;

class CookieFactory
{
	private $cryptoSystem;

	function __construct (iCryptoSystem $cryptoSystem)
	{
		$this->cryptoSystem = $cryptoSystem;
	}

	function create ($name)
	{
		$cookie = new EncryptedCookie ($name);
		$cookie->setCryptoSystem($this->cryptoSystem);

		return $cookie;
	}

	function get ($name)
	{
		$cookie = new EncryptedCookie ($name);
		$cookie->setCryptoSystem($this->cryptoSystem)->load();

		return $cookie;
	}
}

Fix iCryptoSystem missing, shorten function names, fix chaining issue


<?php

namespace Prolougetech\Big;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->mergeConfigFrom(__DIR__ . '/../config/prologue-big.php', 'services');
    }

    /**
     * Register bindings for our big wrapper in our container
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Big::class, function ($app) {
            return new Big();
        });
    }

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

<?php

namespace Prolougetech\Big;

use Illuminate\Support\ServiceProvider;

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

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = __DIR__ . '/../config/prologue-big.php';
        $this->publishes([
            $configPath => config_path('prologue-big.php'),
        ], 'config');
    }

    /**
     * Register bindings for our big wrapper in our container
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__ . '/../config/prologue-big.php', 'prologue-big');

        $this->app->singleton(Big::class, function ($app) {
            return new Big();
        });
    }

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

Fix publishing our config file.

Fix publishing our config file.


<?php

/**
 * Spigot Timings Parser
 *
 * Written by Aikar <aikar@aikar.co>
 *
 * @license MIT
 */
class MinuteReport {
    use FromJson;
    /**
     * @index t
     * @var int
     */
    public $time;

    /**
     * @var float
     */
    public $tps;
    /**
     * @index tick
     * @var TicksRecord
     */
    public $ticks;
    /**
     * @var PingRecord
     */
    public $ping;

}

<?php

/**
 * Spigot Timings Parser
 *
 * Written by Aikar <aikar@aikar.co>
 *
 * @license MIT
 */
class MinuteReport {
    use FromJson;
    /**
     * @index t
     * @var int
     */
    public $time;

    /**
     * @var float
     */
    public $tps;
    /**
     * @index tick
     * @var TicksRecord
     */
    public $ticks;
    /**
     * @var PingRecord
     */
    public $ping;

    /**
     * @index fst
     * @var TimingData
     */
    public $fullServerTick;

}

Add FST to minute reports

Add FST to minute reports


<?php namespace Orchestra\Support\Traits;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Redirect;
use Orchestra\Support\Facades\Messages;

trait ControllerResponseTrait
{
    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  string  $message
     * @param  string  $type
     * @return Response
     */
    public function redirectWithMessage($to, $message = null, $type = 'success')
    {
        ! is_null($message) && Messages::add($type, $message);

        return $this->redirect($to);
    }

    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  mixed   $errors
     * @return Response
     */
    public function redirectWithErrors($to, $errors)
    {
        return $this->redirect($to)->withInput()->withErrors($errors);
    }

    /**
     * Redirect.
     *
     * @param  string  $to
     * @param  string  $message
     * @param  string  $type
     * @return Response
     */
    public function redirect($to)
    {
        return Redirect::to($to);
    }

    /**
     * Halt current request using App::abort().
     *
     * @param  integer $status
     * @return Response
     */
    public function suspend($status)
    {
        return App::abort($status);
    }
}

<?php namespace Orchestra\Support\Traits;

use Illuminate\Support\Facades\App;
use Orchestra\Support\Facades\Messages;
use Illuminate\Support\Facades\Redirect;
use Symfony\Component\HttpKernel\Exception\HttpException
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException

trait ControllerResponseTrait
{
    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  string  $message
     * @param  string  $type
     * @return mixed
     */
    public function redirectWithMessage($to, $message = null, $type = 'success')
    {
        ! is_null($message) && Messages::add($type, $message);

        return $this->redirect($to);
    }

    /**
     * Queue notification and redirect.
     *
     * @param  string  $to
     * @param  mixed   $errors
     * @return mixed
     */
    public function redirectWithErrors($to, $errors)
    {
        return $this->redirect($to)->withInput()->withErrors($errors);
    }

    /**
     * Redirect.
     *
     * @param  string  $to
     * @return mixed
     */
    public function redirect($to)
    {
        return Redirect::to($to);
    }

    /**
     * Halt current request using App::abort().
     *
     * @param  int  $code
     * @return void
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function suspend($code)
    {
        if ($status == 404) {
            throw new NotFoundHttpException('');
        }

        throw new HttpException($code, '', null, []);
    }
}

Handle App::abort() no longer exist.

Handle App::abort() no longer exist.

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


<?php

namespace App\Http\Controllers;

use Socialite;
use Storage;
use GuzzleHttp\Client;

class AuthController extends Controller
{

    public function authorizeSlack()
    {
         $code=$_GET['code'];
$client=new Client();
             $response=$client->request('POST', 'https://slack.com/api/oauth.access',
['json' => ['client_id' => env('SLACK_CLIENT_ID'),
'client_secret' => env('SLACK_CLIENT_SECRET'),
'code' => $code]]);
$response=json_decode($response->getBody(), true);
if($response['ok']===true) {
if(isset($response['access_token'])) {
Storage::put('token.dat', $response['access_token']);
}
else {
Storage::put('token.dat', $response['stuff']['access_token']);
}
$result="Authorized";
}
else {
$result=$response['error'];
}
return view('authorize', ['result' => $result]);
    }

    /* Redirects user to Slack Authetication page
    *
    * @return Response
    */

    public function redirectToProvider()
    {
       return Socialite::driver('slack')->redirect();
    }

    /**
    * Obtain the user information from Slack.
    *
    * @return Response
    */
   public function handleProviderCallback()
   {
       // $user = Socialite::driver('slack')->user();
       $user = Socialite::with('slack')->user();
       var_dump($user);
   }
}

<?php

namespace App\Http\Controllers;

use Socialite;
use Storage;
use GuzzleHttp\Client;

class AuthController extends Controller
{

    public function authorizeSlack()
    {
         $code=$_GET['code'];
$client=new Client();
             $response=$client->request('POST', 'https://slack.com/api/oauth.access',
['json' => ['client_id' => env('SLACK_CLIENT_ID'),
'client_secret' => env('SLACK_CLIENT_SECRET'),
'code' => $code]]);
$response=json_decode($response->getBody(), true);
if($response['ok']===true) {
if(isset($response['access_token'])) {
Storage::put('token.dat', $response['access_token']);
Storage::put('bot_id.dat', $response['bot']['bot_user_id']);
Storage::put('bot_token.dat', $response['bot']['bot_access_token']);
}
else {
Storage::put('token.dat', $response['stuff']['access_token']);
}
$result="Authorized";
}
else {
$result=$response['error'];
}
return view('authorize', ['result' => $result]);
    }

    /* Redirects user to Slack Authetication page
    *
    * @return Response
    */

    public function redirectToProvider()
    {
       return Socialite::driver('slack')->redirect();
    }

    /**
    * Obtain the user information from Slack.
    *
    * @return Response
    */
   public function handleProviderCallback()
   {
       // $user = Socialite::driver('slack')->user();
       $user = Socialite::with('slack')->user();
       var_dump($user);
   }
}

Save bot details on authorization

Save bot details on authorization


<?php

namespace Oro\Bundle\EntityBundle\Provider;

use Doctrine\ORM\QueryBuilder;

interface DictionaryValueListProviderInterface
{
    /**
     * Checks whether the provider supports a given entity
     *
     * @param string $className The FQCN of an entity
     *
     * @return bool TRUE if this provider supports the given entity; otherwise, FALSE
     */
    public function supports($className);

    /**
     * Gets a query builder for getting dictionary item values for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return QueryBuilder
     */
    public function getValueListQueryBuilder($className);

    /**
     * Gets the configuration of the entity serializer for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return array
     */
    public function getSerializationConfig($className);

    /**
     * Gets a list of entity classes supported by this provider
     *
     * @return string[]
     */
    public function getSupportedEntityClasses();
}

OEE-620: Create REST API resource to get dictionary/enum items. Fix CS


<?php

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

namespace Symfony\Bundle\WebServerBundle\DependencyInjection;

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

/**
 * @author Robin Chalas <robin.chalas@gmail.com>
 */
class WebServerExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('webserver.xml');
    }
}

<?php

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

namespace Symfony\Bundle\WebServerBundle\DependencyInjection;

use Symfony\Bridge\Monolog\Formatter\ConsoleFormatter;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;

/**
 * @author Robin Chalas <robin.chalas@gmail.com>
 */
class WebServerExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('webserver.xml');

        if (!class_exists(ConsoleFormatter::class)) {
            $container->removeDefinition('web_server.command.server_log');
        }
    }
}

Remove the `server:log` command if monolog is not loaded


<?php

//config file
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

//required libs
require_once 'smarty/smarty/libs/Smarty.class.php';

//initialize smarty
$smarty = new Smarty();
$smarty->setTemplateDir(SHARE_DIR . DIRECTORY_SEPARATOR . 'smarty' . DIRECTORY_SEPARATOR . 'templates');
$smarty->setCompileDir(VAR_DIR . DIRECTORY_SEPARATOR . 'smarty' . DIRECTORY_SEPARATOR . 'templates_c');
$smarty->setCacheDir(VAR_DIR . DIRECTORY_SEPARATOR . 'smarty' . DIRECTORY_SEPARATOR . 'cache');
$smarty->left_delimiter = '{#';
$smarty->right_delimiter = '#}';

$smarty->assign('WebRoot', WEBROOT);
$smarty->assign('ServicePath', SERVICEPATH);

$smarty->assign('fennec_version', '0.0.1');
$smarty->display('startpage.tpl');

?>

<?php

//config file
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php';

//required libs
require_once 'smarty/smarty/libs/Smarty.class.php';

//initialize smarty
$smarty = new Smarty();
$smarty->setTemplateDir(SHARE_DIR . DIRECTORY_SEPARATOR . 'smarty' . DIRECTORY_SEPARATOR . 'templates');
$smarty->setCompileDir(VAR_DIR . DIRECTORY_SEPARATOR . 'smarty' . DIRECTORY_SEPARATOR . 'templates_c');
$smarty->setCacheDir(VAR_DIR . DIRECTORY_SEPARATOR . 'smarty' . DIRECTORY_SEPARATOR . 'cache');
$smarty->left_delimiter = '{#';
$smarty->right_delimiter = '#}';

$smarty->assign('WebRoot', WEBROOT);
$smarty->assign('ServicePath', SERVICEPATH);

$smarty->assign('fennec_version', '0.0.1');

$page = requestVal('page', '/^[a-z-_\.]*$/', '');
switch ($page) {
    case 'organism':
        $smarty->assign('navbar_type', 'organism');
        $smarty->display('organism.tpl');
        die();
}
$smarty->assign('navbar_type', 'startpage');
$smarty->display('startpage.tpl');

/**
 * returns $_REQUEST[$key] value if it matches $regexp, else return $defaultvalue
 * @param String $key
 * @param String $regexp
 * @param String $defaultvalue
 * @return String
 */
function requestVal($key, $regexp = "/^.*$/", $defaultvalue = "") {
    if (!isset($_REQUEST[$key]) || !preg_match($regexp, $_REQUEST[$key]))
        return $defaultvalue;
    else
        return $_REQUEST[$key];
}
?>

Add switch case statement for defining the organism page and set the navbar type


<?php

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

class CreateMachineSurveydataTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('machine_surveydata', function (Blueprint $table) {
            $table->integer('id')->unsigned();
            $table->integer('machine_id')->unsigned()->nullable()->default(null);
            $table->boolean('gendata')->nullable()->default(null);
            $table->boolean('collimatordata')->nullable()->default(null);
            $table->boolean('radoutputdata')->nullable()->default(null);
            $table->boolean('radsurveydata')->nullable()->default(null);
            $table->boolean('hvldata')->nullable()->default(null);
            $table->boolean('fluorodata')->nullable()->default(null);
            $table->boolean('maxfluorodata')->nullable()->default(null);
            $table->boolean('receptorentrance')->nullable()->default(null);
            $table->index(['machine_id', 'id']);
            $table->softDeletes();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

->default(0)<?php

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

class CreateMachineSurveydataTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('machine_surveydata', function (Blueprint $table) {
            $table->integer('id')->unsigned();
            $table->integer('machine_id')->unsigned()->default(0);
            $table->boolean('gendata')->default(0);
            $table->boolean('collimatordata')->default(0);
            $table->boolean('radoutputdata')->default(0);
            $table->boolean('radsurveydata')->default(0);
            $table->boolean('hvldata')->default(0);
            $table->boolean('fluorodata')->default(0);
            $table->boolean('maxfluorodata')->default(0);
            $table->boolean('receptorentrance')->default(0);
            $table->index(['machine_id', 'id']);
            $table->softDeletes();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Change field defaults from NULL to 0

Change field defaults from NULL to 0

MariaDB doesn't seem to like numeric/boolean fields to have NULL for a
default value


<?php

namespace
{
    require __DIR__.'/../vendor/autoload.php';
}

namespace Cache\IntegrationTests
{
    if (!class_exists('Cache\IntegrationTests\CachePoolTest')) {
        class CachePoolTest extends \PHPUnit_Framework_TestCase
        {
            public function testIncomplete()
            {
                $this->markTestIncomplete(
                    'Missing dependencies. Please run: '.
                    'composer require --dev cache/integration-tests:dev-master'
                );
            }
        }
    }
}

<?php

namespace
{
    require __DIR__.'/../vendor/autoload.php';
}

namespace Cache\IntegrationTests
{
    // PSR-6 integration tests
    if (!class_exists('Cache\IntegrationTests\CachePoolTest')) {
        class CachePoolTest extends \PHPUnit_Framework_TestCase
        {
            public function testIncomplete()
            {
                $this->markTestIncomplete(
                    'Missing dependencies. Please run: '.
                    'composer require --dev cache/integration-tests:dev-master'
                );
            }
        }
    }

    // PSR-16 integration tests
    if (!class_exists('Cache\IntegrationTests\SimpleCacheTest')) {
        class SimpleCacheTest extends \PHPUnit_Framework_TestCase
        {
            public function testIncomplete()
            {
                $this->markTestIncomplete(
                    'Missing dependencies. Please run: '.
                    'composer require --dev cache/integration-tests:dev-master'
                );
            }
        }
    }
}

Make sure tests don't fail when integration tests not loaded


<?php

namespace Heystack\Subsystem\Core\Console;

use Monolog\Logger;
use Symfony\Component\Console\Application as BaseApplication;

/**
 * Class Application
 * @package Heystack\Subsystem\Core\Console
 */
class Application extends BaseApplication
{
    /**
     * @var
     */
    protected $logger;
    /**
     *
     */
    public function __construct()
    {
        parent::__construct('Heystack', '1.1');
    }
    /**
     * @param Logger $logger
     */
    public function setLogger(Logger $logger)
    {
        $this->logger = $logger;
    }
    /**
     * @return Logger
     */
    public function getLogger()
    {
        return $this->logger;
    }
}

<?php

namespace Heystack\Subsystem\Core\Console;

use Monolog\Logger;
use Symfony\Component\Console\Application as BaseApplication;

/**
 * Class Application
 * @package Heystack\Subsystem\Core\Console
 */
class Application extends BaseApplication
{
    /**
     * @var
     */
    protected $logger;
    /**
     *
     */
    public function __construct()
    {
        parent::__construct('Heystack', '2.1.1');
    }
    /**
     * @param Logger $logger
     */
    public function setLogger(Logger $logger)
    {
        $this->logger = $logger;
    }
    /**
     * @return Logger
     */
    public function getLogger()
    {
        return $this->logger;
    }
}

Increment version number of console application fixes T71

Reviewers: stevie, glenn

Reviewed By: stevie

Maniphest Tasks: T71

Differential Revision: https://phabricator.heyday.net.nz/D42


<?php

namespace Sabre\VObject;

class WriterTest extends \PHPUnit_Framework_TestCase {

    function getComponent() {

        $data = "BEGIN:VCALENDAR\r\nEND:VCALENDAR";
        return Reader::read($data);

    }

    function testWriteToMimeDir() {

        $result = Writer::write($this->getComponent());
        $this->assertEquals("BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n", $result);

    }

    function testWriteToJson() {

        $result = Writer::writeJson($this->getComponent());
        $this->assertEquals('["vcalendar",[],[]]', $result);

    }

    function testWriteToXml() {

        $result = Writer::writeXml($this->getComponent());
        $this->assertEquals(
            '<?xml version="1.0" encoding="UTF-8"?>' . "\n" .
            '<icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0">' . "\n" .
            ' <vcalendar/>' . "\n" .
            '</icalendar>' . "\n",
            $result
        );

    }

}

<?php

namespace Sabre\VObject;

class WriterTest extends \PHPUnit_Framework_TestCase {

    function getComponent() {

        $data = "BEGIN:VCALENDAR\r\nEND:VCALENDAR";
        return Reader::read($data);

    }

    function testWriteToMimeDir() {

        $result = Writer::write($this->getComponent());
        $this->assertEquals("BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n", $result);

    }

    function testWriteToMimeDirWithIterator() {

        $iterator = function() {
            for($i = 0; $i < 3; ++$i) {
                yield $this->getComponent();
            }
        };

        $result = Writer::write($iterator());
        $this->assertEquals(
            "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n" .
            "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n" .
            "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n",
            $result
        );

    }

    function testWriteToJson() {

        $result = Writer::writeJson($this->getComponent());
        $this->assertEquals('["vcalendar",[],[]]', $result);

    }

    function testWriteToXml() {

        $result = Writer::writeXml($this->getComponent());
        $this->assertEquals(
            '<?xml version="1.0" encoding="UTF-8"?>' . "\n" .
            '<icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0">' . "\n" .
            ' <vcalendar/>' . "\n" .
            '</icalendar>' . "\n",
            $result
        );

    }

}

Add a test for Writer + MIME Dir + iterator.


Pending surveys

			Survey ID
            Description
            Date Scheduled
            Test type
            Accession
            Survey Note

@foreach ($pendingSurveys as $pending)

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

@endforeach

Pending surveys

			Survey ID
            Description
            Date Scheduled
            Test type
            Accession
            Survey Note

@foreach ($pendingSurveys as $pending)

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

@endforeach

Fix survey ID, machine description display