<?php
/**
 * @package Puzzle-DI
 * @copyright Copyright © 2015 Danny Smart
 */

namespace Lexide\PuzzleDI\Plugin;

use Composer\Composer;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Script\Event;
use Composer\Script\ScriptEvents;
use Lexide\PuzzleDI\Controller\ScriptController;

class PuzzlePlugin implements PluginInterface, EventSubscriberInterface
{
    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            ScriptEvents::POST_INSTALL_CMD => ['runPlugin'],
            ScriptEvents::POST_UPDATE_CMD => ['runPlugin']
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function activate(Composer $composer, IOInterface $io)
    {
        // move along, nothing to see here
    }

    /**
     * @param Event $event
     */
    public function runPlugin(Event $event)
    {
        $controller = new ScriptController();
        $controller->compileConfigList($event);
    }

}

<?php
/**
 * @package Puzzle-DI
 * @copyright Copyright © 2015 Danny Smart
 */

namespace Lexide\PuzzleDI\Plugin;

use Composer\Composer;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Script\Event;
use Composer\Script\ScriptEvents;
use Lexide\PuzzleDI\Controller\ScriptController;

class PuzzlePlugin implements PluginInterface, EventSubscriberInterface
{
    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            ScriptEvents::POST_INSTALL_CMD => ['runPlugin'],
            ScriptEvents::POST_UPDATE_CMD => ['runPlugin']
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function activate(Composer $composer, IOInterface $io)
    {
        // move along, nothing to see here
    }

    /**
     * @param Event $event
     */
    public function runPlugin(Event $event)
    {
        // If puzzle has been removed in this update, the script controller may no longer exist
        if (!class_exists("\\Lexide\\PuzzleDI\\Controller\\ScriptController")) {
            return;
        }

        $controller = new ScriptController();
        $controller->compileConfigList($event);
    }

}

Fix "class not found" bug when removing puzzle from composer


<?php

namespace Kula\Core\Bundle\SystemBundle\Controller;

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

class CoreTermsController extends Controller {

  public function indexAction() {
    $this->authorize();
    $this->processForm();

    // Get terms
    $terms = $this->db()->db_select('CORE_TERM')
      ->fields('CORE_TERM')
      ->orderBy('START_DATE', 'ASC')
      ->orderBy('END_DATE', 'ASC')
      ->orderBy('TERM_ABBREVIATION', 'ASC')
      ->orderBy('TERM_NAME', 'ASC')
      ->execute()->fetchAll();

    return $this->render('KulaCoreSystemBundle:Terms:index.html.twig', array('terms' => $terms));
  }

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

<?php

namespace Kula\Core\Bundle\SystemBundle\Controller;

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

class CoreTermsController extends Controller {

  public function indexAction() {
    $this->authorize();
    $this->processForm();

    $term_service = $this->get('kula.core.term');

    // Get terms
    $terms = $this->db()->db_select('CORE_TERM')
      ->fields('CORE_TERM')
      ->condition('START_DATE', $term_service->getStartDate($this->focus->getTermID()), '>=')
      ->orderBy('START_DATE', 'ASC')
      ->orderBy('END_DATE', 'ASC')
      ->orderBy('TERM_ABBREVIATION', 'ASC')
      ->orderBy('TERM_NAME', 'ASC')
      ->execute()->fetchAll();

    return $this->render('KulaCoreSystemBundle:Terms:index.html.twig', array('terms' => $terms));
  }

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

Fix terms to only show terms ahead of focused term.


<?php

final class PhabricatorPronounSetting
  extends PhabricatorSelectSetting {

  const SETTINGKEY = 'pronoun';

  public function getSettingName() {
    return pht('Pronoun');
  }

  public function getSettingPanelKey() {
    return PhabricatorAccountSettingsPanel::PANELKEY;
  }

  protected function getSettingOrder() {
    return 200;
  }

  protected function getControlInstructions() {
    return pht('Choose the pronoun you prefer.');
  }

  public function getSettingDefaultValue() {
    return PhutilPerson::SEX_UNKNOWN;
  }

  protected function getSelectOptions() {
    // TODO: When editing another user's settings as an administrator, this
    // is not the best username: the user's username would be better.

    $viewer = $this->getViewer();
    $username = $viewer->getUsername();

    $label_unknown = pht('%s updated their profile', $username);
    $label_her = pht('%s updated her profile', $username);
    $label_his = pht('%s updated his profile', $username);

    return array(
      PhutilPerson::SEX_UNKNOWN => $label_unknown,
      PhutilPerson::SEX_MALE => $label_his,
      PhutilPerson::SEX_FEMALE => $label_her,
    );
  }

}

<?php

final class PhabricatorPronounSetting
  extends PhabricatorSelectSetting {

  const SETTINGKEY = 'pronoun';

  public function getSettingName() {
    return pht('Pronoun');
  }

  public function getSettingPanelKey() {
    return PhabricatorAccountSettingsPanel::PANELKEY;
  }

  protected function getSettingOrder() {
    return 200;
  }

  protected function getControlInstructions() {
    return pht('Choose the pronoun you prefer.');
  }

  public function getSettingDefaultValue() {
    return PhutilPerson::GENDER_UNKNOWN;
  }

  protected function getSelectOptions() {
    // TODO: When editing another user's settings as an administrator, this
    // is not the best username: the user's username would be better.

    $viewer = $this->getViewer();
    $username = $viewer->getUsername();

    $label_unknown = pht('%s updated their profile', $username);
    $label_her = pht('%s updated her profile', $username);
    $label_his = pht('%s updated his profile', $username);

    return array(
      PhutilPerson::GENDER_UNKNOWN => $label_unknown,
      PhutilPerson::GENDER_MASCULINE => $label_his,
      PhutilPerson::GENDER_FEMININE => $label_her,
    );
  }

}

Fix some grammatical gender constants

Fix some grammatical gender constants

Summary: Ref T5267. I missed these in the variable types conversion.

Test Plan: `arc unit --everything`

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T5267

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


<?php

namespace Onceit\RaygunBundle\Raygun;

use Raygun4php\RaygunClient;

class Client extends RaygunClient
{
    /**
     * {@inheritDoc}
     */
    public function Send($message)
    {
        if (empty($this->apiKey)) {
            return;
        }

        return call_user_func_array('parent::__construct', func_get_args());
    }
}

<?php

namespace Onceit\RaygunBundle\Raygun;

use Raygun4php\RaygunClient;

class Client extends RaygunClient
{
    /**
     * {@inheritDoc}
     */
    public function Send($message)
    {
        if (empty($this->apiKey)) {
            return;
        }

        return parent::Send($message);
    }
}

Call parent::Send rather then parent::__construct - whoops


<?php

namespace SlmQueueBeanstalkd\Worker\Exception;

use SlmQueue\Exception\ExceptionInterface;
use InvalidArgumentException;

class InvalidQueueException extends InvalidArgumentException implements ExceptionInterface
{

}

<?php

namespace SlmQueueBeanstalkd\Worker\Exception;

use SlmQueueBeanstalkd\Exception\ExceptionInterface;
use InvalidArgumentException;

class InvalidQueueException extends InvalidArgumentException implements ExceptionInterface
{

}

Use the new Beanstalkd ExceptionInterface


<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class ApiController {
	/**
	 * @Route("/api/submit")
	 */
	public function submitAction(Request $request) {

		$dataRaw = $request->request->get('data');
		if ($dataRaw === NULL) {
			exit("Error");
		}

		$client = new \Elasticsearch\Client();
		$params = array();
		$params['body'] = json_decode($dataRaw);
		$params['index'] = 'weather_station';
		$params['type'] = 'weatherStationLog';
		$ret = $client->index($params);
		return new JsonResponse(array('status' => 'OK'));
	}

	/**
	 * @param int $limit
	 */
	public function readAction($limit = 100) {
		$client = new \Elasticsearch\Client();

		$searchParams['body']['query']['match']['testField'] = 'abc';
	}
}

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class ApiController {
	/**
	 * @Route("/api/submit")
	 */
	public function submitAction(Request $request) {
		$dataRaw = $request->request->get('data');
		$clientIP = $request->getClientIp();
		$currentDate = new \DateTime();
		if ($dataRaw === NULL) {
			exit("Error");
		}

		$storedData = json_decode($dataRaw, true);
		$storedData['timestamp'] = $currentDate->format('d/m-Y H:i:s');
		$storedData['clientIp'] = $clientIP;
		$client = new \Elasticsearch\Client();
		$params = array();
		$params['body'] = $storedData;
		$params['index'] = 'weather_station';
		$params['type'] = 'weatherStationLog';
		$client->index($params);
		return new JsonResponse(array('status' => 'OK'));
	}

	/**
	 * @param int $limit
	 */
	public function readAction($limit = 100) {
		$client = new \Elasticsearch\Client();

		$searchParams['body']['query']['match']['testField'] = 'abc';
	}
}

Add timestamp and client IP

Add timestamp and client IP


<?// Display form wide errors?>

<? if (!empty($errors) && !empty($errors->messages)): ?>

	  <button type="button" class="close" data-dismiss="alert">×</button>
	  Validation Error!

	  <?// Special duplicate slug method?>
	  <? if (in_array('slug', array_keys($errors->messages))): ?>
	  	A unique slug could not be formed from the name or title.  You must use a different value.

	  <?// Generic error message?>
	  <? else: ?>
	  	<? if (count($errors->messages) > 1): ?>
	  		The fields in conflict are highlighted below.
		  <? else: ?>
	  		The field in conflict is highlighted below.
		  <? endif ?>
		<? endif ?>

<? endif ?>

<?// Display form wide errors?>

<? if (!empty($errors) && !empty($errors->messages)): ?>

<? if(Config::get('error.log') == true) Log::info(print_r($errors, true)); ?>

	  <button type="button" class="close" data-dismiss="alert">×</button>
	  Validation Error!

	  <?// Special duplicate slug method?>
	  <? if (in_array('slug', array_keys($errors->messages))): ?>
	  	A unique slug could not be formed from the name or title.  You must use a different value.

	  <?// Generic error message?>
	  <? else: ?>
	  	<? if (count($errors->messages) > 1): ?>
	  		The fields in conflict are highlighted below.
		  <? else: ?>
	  		The field in conflict is highlighted below.
		  <? endif ?>
		<? endif ?>

<? endif ?>

Set up Laravel error logging for form based errors.


<?php
/**
 * @file
 * @version 0.1
 * @copyright 2017 CN-Consult GmbH
 * @author Yannick Lapp <yannick.lapp@cn-consult.eu>
 */

/**
 * Class Psr4Autoloader
 */
class Psr4Autoloader
{
    private $prefixes = array();

    /**
     * register all prefixes that are saved in the object
     */
    public function register()
    {
        spl_autoload_register(
            function ($_class)
            {
                foreach ($this->prefixes as $prefix=>$baseDirectory)
                {
                    // check whether class uses the namespace prefix
                    $len = strlen($prefix);

                    if (strncmp($prefix, $_class, $len) === 0)
                    {
                        $relativeClass = substr($_class, $len);

                        $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php';

                        if (file_exists($file))
                        {
                            require_once $file;
                        }
                    }
                }
            }
        );
    }

    /**
     * add a namespace to the list
     *
     * @param string $_prefix       namespace prefix
     * @param string $_baseDir     filepath prefix
     */
    public function addNamespace($_prefix, $_baseDir)
    {
        // initialize the namespace prefix array
        if (isset($this->prefixes[$_prefix]) === false)
        {
            $this->prefixes[$_prefix] = array();
        }

        $this->prefixes[$_prefix] = $_baseDir;
    }
}

<?php
/**
 * @file
 * @version 0.1
 * @copyright 2017 CN-Consult GmbH
 * @author Yannick Lapp <yannick.lapp@cn-consult.eu>
 */

/**
 * Class Psr4Autoloader
 */
class Psr4Autoloader
{
    private $prefixes = array();

    /**
     * register all prefixes that are saved in the object
     */
    public function register()
    {
        spl_autoload_register(
            function ($_class)
            {
                foreach ($this->prefixes as $prefix=>$baseDirectory)
                {
                    // check whether class uses one of the namespace prefixes
                    $len = strlen($prefix);

                    if (strncmp($prefix, $_class, $len) === 0)
                    {
                        $relativeClass = substr($_class, $len);

                        $file = $baseDirectory . str_replace('\\', '/', $relativeClass) . '.php';

                        if (file_exists($file)) require_once $file;
                    }
                }
            }
        );
    }

    /**
     * add a namespace to the list
     *
     * @param string $_prefix      namespace prefix
     * @param string $_baseDir     filepath prefix
     */
    public function addNamespace($_prefix, $_baseDir)
    {
        if (isset($this->prefixes[$_prefix]) === false)
        {
            $this->prefixes[$_prefix] = $_baseDir;
        }
    }
}

Remove unnecessary code from autloader

Remove unnecessary code from autloader

Removed unnecessary code.


<?php

namespace mostertb\PhpJhbOpenBios\bios;

class BradMostertBio extends AbstractBio
{

    /**
     * Provides the full name of the person that the bio is about
     *
     * @return string
     */
    public function getName()
    {
        return 'Brad Mostert';
    }

    /**
     * Provides a paragraph of test about the person that the bio is about
     *
     * @return string
     */
    public function getDescription()
    {
        return 'Renegade that makes projects like this to mess with the status quo. I like long walks on the beach and '.
            'craft beer.';
    }

    /**
     * Should return a publicly accessible URL to an image of the person that the bio is about.
     *
     * @return null|string
     */
    public function getProfileImageURL()
    {
        return 'http://i.imgur.com/dv78K3h.jpg';
    }

}

<?php

namespace mostertb\PhpJhbOpenBios\bios;

class BradMostertBio extends AbstractBio
{

    /**
     * Provides the full name of the person that the bio is about
     *
     * @return string
     */
    public function getName()
    {
        return 'Brad Mostert';
    }

    /**
     * Provides a paragraph of test about the person that the bio is about
     *
     * @return string
     */
    public function getDescription()
    {
        return 'Developer at Afrihost. Design Patterns acolyte. Dangerous sysadmin using \'DevOps\' as an excuse. I like '.
            'long walks on the beach and craft beer.';
    }

    /**
     * Should return a publicly accessible URL to an image of the person that the bio is about.
     *
     * @return null|string
     */
    public function getProfileImageURL()
    {
        return 'https://s.gravatar.com/avatar/9ff2a97e7faf3529f1b78f1f737ebca0?s=80';
    }

    public function getGitHubUsername()
    {
        return 'mostertb';
    }

    public function getMaintainedProjects()
    {
        return array(
          'Afrihost/BaseCommandBundle' => 'https://github.com/afrihost/BaseCommandBundle'
        );
    }

}

Update my Bio for 2016

Update my Bio for 2016


<?php
/**
 * @file
 * Contains \Drupal\AppConsole\Command\GeneratorEntityConfigCommand.
 */

namespace Drupal\AppConsole\Command;

class GeneratorEntityConfigCommand extends GeneratorEntityCommand {

  protected function configure()
  {
    parent::configure();
  }
}

<?php
/**
 * @file
 * Contains \Drupal\AppConsole\Command\GeneratorEntityConfigCommand.
 */

namespace Drupal\AppConsole\Command;

class GeneratorEntityConfigCommand extends GeneratorEntityCommand {

  protected function configure()
  {
    $this->setEntityType('EntityConfig');
    $this->setCommandName('generate:entity:config');
    parent::configure();
  }
}

Use new setter methods at parent class

Use new setter methods at parent class


<?php

namespace DataDog\AuditBundle\DependencyInjection;

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

/**
 * Configuration for DataDog/AuditBundle
 */
class Configuration implements ConfigurationInterface
{

    /**
     * {@inheritDoc}
     * @see \Symfony\Component\Config\Definition\ConfigurationInterface::getConfigTreeBuilder()
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('data_dog_audit');

        $rootNode
            ->children()
                ->arrayNode('audited_entities')
                    ->canBeUnset()
                    ->performNoDeepMerging()
                    ->prototype('scalar')->end()
                ->end()
            ->end()
        ;

        $rootNode
            ->children()
                ->arrayNode('unaudited_entities')
                    ->canBeUnset()
                    ->performNoDeepMerging()
                    ->prototype('scalar')->end()
                ->end()
            ->end()
        ;

        $rootNode
            ->children()
                ->booleanNode('blame_impersonator')
                ->defaultFalse()
            ->end()
        ;

        return $treeBuilder;
    }

}

<?php

namespace DataDog\AuditBundle\DependencyInjection;

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

/**
 * Configuration for DataDog/AuditBundle
 */
class Configuration implements ConfigurationInterface
{

    /**
     * {@inheritDoc}
     * @see \Symfony\Component\Config\Definition\ConfigurationInterface::getConfigTreeBuilder()
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('data_dog_audit');
        // BC layer for symfony/config < 4.2
        $rootNode = method_exists($treeBuilder, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('data_dog_audit');

        $rootNode
            ->children()
                ->arrayNode('audited_entities')
                    ->canBeUnset()
                    ->performNoDeepMerging()
                    ->prototype('scalar')->end()
                ->end()
            ->end()
        ;

        $rootNode
            ->children()
                ->arrayNode('unaudited_entities')
                    ->canBeUnset()
                    ->performNoDeepMerging()
                    ->prototype('scalar')->end()
                ->end()
            ->end()
        ;

        $rootNode
            ->children()
                ->booleanNode('blame_impersonator')
                ->defaultFalse()
            ->end()
        ;

        return $treeBuilder;
    }

}

Update config tree builder constructor

Update config tree builder constructor


<?php

namespace Joe1992w\LaravelMediaEmbed\Services;

use MediaEmbed\MediaEmbed;

class LaravelMediaEmbed
{
  public function parse($url = null, $whitelist = [], $params = [], $attributes = []) {

    $MediaEmbed = new MediaEmbed();

    $MediaObject = $MediaEmbed->parseUrl($url);

    if ($MediaObject)
    {

      if(is_array($params))
      {
        $MediaObject->setParam($params);
      }

      if(is_array($params))
      {
        $MediaObject->setAttribute($attributes);
      }

      if (!empty($whitelist))
      {

        if(!in_array($MediaObject->name(), $whitelist))
        {

          return false;

        }

      }

      return $MediaObject->getEmbedCode();

    }

    return false;

  }

}

<?php

namespace Joe1992w\LaravelMediaEmbed\Services;

use MediaEmbed\MediaEmbed;

class LaravelMediaEmbed
{
  public function parse($url = null, $whitelist = [], $params = [], $attributes = []) {

    $MediaEmbed = new MediaEmbed();

    $MediaObject = $MediaEmbed->parseUrl($url);

    if ($MediaObject)
    {

      if(is_array($params))
      {
        $MediaObject->setParam($params);
      }

      if(is_array($params))
      {
        $MediaObject->setAttribute($attributes);
      }

      if (!empty($whitelist))
      {

        if(!in_array($MediaObject->name(), $whitelist))
        {

          return false;

        }

      }

      return $MediaObject;

    }

    return false;

  }

}

Return MediaObject class instead of string

__toString method on object returns embed URL as before so no usage
changes required


<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Bundle\QrCodeBundle\Controller;

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

use Endroid\QrCode\QrCode;

/**
 * QR code controller.
 */
class QrCodeController extends Controller
{
    /**
     *
     * @Route("/{text}.{extension}", name="endroid_qrcode", requirements={"text"="[^/\\]+", "extension"="jpg|png|gif"})
     *
     */
    public function generateAction($text, $extension)
    {
        $qrCode = new QrCode();
        $qrCode->setText($text);
        $qrCode = $qrCode->get($extension);

        $mime_type = 'image/'.$extension;
        if ($extension == 'jpg') {
            $mime_type = 'image/jpeg';
        }

        return new Response($qrCode, 200, array('Content-Type' => $mime_type));
    }
}

<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\Bundle\QrCodeBundle\Controller;

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

use Endroid\QrCode\QrCode;

/**
 * QR code controller.
 */
class QrCodeController extends Controller
{
    /**
     *
     * @Route("/{text}.{extension}", name="endroid_qrcode", requirements={"text"="[\w\W]+", "extension"="jpg|png|gif"})
     *
     */
    public function generateAction($text, $extension)
    {
        $qrCode = new QrCode();
        $qrCode->setText($text);
        $qrCode = $qrCode->get($extension);

        $mime_type = 'image/'.$extension;
        if ($extension == 'jpg') {
            $mime_type = 'image/jpeg';
        }

        return new Response($qrCode, 200, array('Content-Type' => $mime_type));
    }
}

Allow slashes and backslashes in the code's content.


<?php

declare(strict_types=1);

/*
 * This file is part of gpupo/common
 * Created by Gilmar Pupo <contact@gpupo.com>
 * For the information of copyright and license you should read the file
 * LICENSE which is distributed with this source code.
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
 * LICENSE que é distribuído com este código-fonte.
 * Para obtener la información de los derechos de autor y la licencia debe leer
 * el archivo LICENSE que se distribuye con el código fuente.
 * For more information, see <https://opensource.gpupo.com/>.
 *
 */

use Symfony\Component\Dotenv\Dotenv;

if (!class_exists('\Gpupo\Common\Console\Application')) {
    require __DIR__.'/../vendor/autoload.php';
}

if (!class_exists(Dotenv::class)) {
    throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
// load all the .env files
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env');

<?php

declare(strict_types=1);

/*
 * This file is part of gpupo/common
 * Created by Gilmar Pupo <contact@gpupo.com>
 * For the information of copyright and license you should read the file
 * LICENSE which is distributed with this source code.
 * Para a informação dos direitos autorais e de licença você deve ler o arquivo
 * LICENSE que é distribuído com este código-fonte.
 * Para obtener la información de los derechos de autor y la licencia debe leer
 * el archivo LICENSE que se distribuye con el código fuente.
 * For more information, see <https://opensource.gpupo.com/>.
 *
 */

use Symfony\Component\Dotenv\Dotenv;

if (!class_exists('\Gpupo\Common\Console\Application')) {
    require __DIR__.'/../vendor/autoload.php';
}

if (!class_exists(Dotenv::class)) {
    throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
// load all the .env files
(new Dotenv(true))->loadEnv(dirname(__DIR__).'/.env');

Update Dotenv config to the new version

Update Dotenv config to the new version


<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		WP_CLI::log( ' - Installing package' );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString( $event->getPool() );
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) );
			}
		}

	}

}

<?php

namespace WP_CLI;

use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;

/**
 * A Composer Event subscriber so we can keep track of what's happening inside Composer
 */
class PackageManagerEventSubscriber implements EventSubscriberInterface {

	public static function getSubscribedEvents() {

		return array(
			ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
			ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
			);
	}

	public static function pre_install( PackageEvent $event ) {
		$operation_message = $event->getOperation()->__toString();
		WP_CLI::log( ' - ' . $operation_message );
	}

	public static function post_install( PackageEvent $event ) {

		$operation = $event->getOperation();
		$reason = $operation->getReason();
		if ( $reason instanceof Rule ) {

			switch ( $reason->getReason() ) {

				case Rule::RULE_PACKAGE_CONFLICT;
				case Rule::RULE_PACKAGE_SAME_NAME:
				case Rule::RULE_PACKAGE_REQUIRES:
					$composer_error = $reason->getPrettyString( $event->getPool() );
					break;

			}

			if ( ! empty( $composer_error ) ) {
				WP_CLI::log( sprintf( " - Warning: %s", $composer_error ) );
			}
		}

	}

}

Change installing message in composer dependency


<?php

namespace React\Tests\EventLoop;

class TestCase extends \PHPUnit_Framework_TestCase
{
    protected function expectCallableExactly($amount)
    {
        $mock = $this->createCallableMock();
        $mock
            ->expects($this->exactly($amount))
            ->method('__invoke');

        return $mock;
    }

    protected function expectCallableOnce()
    {
        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke');

        return $mock;
    }

    protected function expectCallableNever()
    {
        $mock = $this->createCallableMock();
        $mock
            ->expects($this->never())
            ->method('__invoke');

        return $mock;
    }

    protected function createCallableMock()
    {
        $stub = 'React\Tests\EventLoop\CallableStub';

        if (method_exists($this, 'createMock')) {
            return $this->createMock($stub);
        }

        return $this->getMock($stub);
    }
}

<?php

namespace React\Tests\EventLoop;

class TestCase extends \PHPUnit_Framework_TestCase
{
    protected function expectCallableExactly($amount)
    {
        $mock = $this->createCallableMock();
        $mock
            ->expects($this->exactly($amount))
            ->method('__invoke');

        return $mock;
    }

    protected function expectCallableOnce()
    {
        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke');

        return $mock;
    }

    protected function expectCallableNever()
    {
        $mock = $this->createCallableMock();
        $mock
            ->expects($this->never())
            ->method('__invoke');

        return $mock;
    }

    protected function createCallableMock()
    {
        return $this->getMockBuilder('React\Tests\EventLoop\CallableStub')->getMock();
    }
}

Switch to mock builder as it works across all PHPUnit versions.


<?php

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

class CreateDiscussionsTable extends Migration
{
    public function up()
    {
        Schema::create('discussions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned();
            $table->integer('topic_id')->unsigned();
            $table->string('title');
            $table->longText('body');
            //$table->string('slug');
            $table->bigInteger('answer_id')->unsigned()->nullable();

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

    public function down()
    {
        Schema::dropIfExists('discussions');
    }
}

<?php

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

class CreateDiscussionsTable extends Migration
{
    public function up()
    {
        Schema::create('discussions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned();
            $table->integer('topic_id')->unsigned();
            $table->bigInteger('answer_id')->unsigned()->nullable();
            $table->string('title');
            $table->longText('body');
            //$table->string('slug');

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

    public function down()
    {
        Schema::dropIfExists('discussions');
    }
}

Change the order of the answer_id field

Change the order of the answer_id field


<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase {
    /* public function testBasicTest() {
        $response = $this->get('/');

        $response->assertStatus(200);
    } */
}

Disable feature test that came with Laravel by default


<?php
/**
 * Plugin Name: E2E Enable Loopback
 * Description: Plugin to filter http requests to remove the port.
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */
add_filter(
	'pre_http_request',
	function ( $preempt, $args, $url ) {
		if ( 'localhost' === parse_url( $url, PHP_URL_HOST ) && 9002 === parse_url( $url, PHP_URL_PORT ) ) {
			$args['headers'] = wp_parse_args( array( 'Host' => $url ), $args['headers'] );
			$no_port_url     = str_replace( ':9002', '', $url );
			$preempt         = wp_remote_request( $no_port_url, $args );
		}
		return $preempt;
	},
	10,
	3
);

<?php
/**
 * Plugin Name: E2E Enable Loopback
 * Description: Plugin to filter http requests to remove the port.
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */
add_filter(
	'pre_http_request',
	function ( $preempt, $args, $url ) {
		if ( 'localhost' === parse_url( $url, PHP_URL_HOST ) && parse_url( $url, PHP_URL_PORT ) ) {
			$args['headers'] = array_merge(
				$args['headers'],
				array( 'Host' => 'localhost:' . parse_url( $url, PHP_URL_PORT ) )
			);

			// Split the URL by the port, but only once.
			list( $http_host, $path ) = preg_split( '/:\d+/', $url, 2 );

			// Return the response from the altered request to the same URL, without the port.
			return wp_remote_request( $http_host . $path, $args );
		}
		return $preempt;
	},
	10,
	3
);

Update loopback plugin to return valid Host header.


<?php
$compileFile = 'SimplePie.compiled.php';
chdir(dirname(dirname(__FILE__)));
`cat SimplePie.php > $compileFile.tmp`;
`find SimplePie -type f| xargs cat | sed 's/^<?php//g'>>$compileFile.tmp`;

$contents = file_get_contents("$compileFile.tmp");
$tokens = token_get_all($contents);
$stripped_source = '';
foreach ($tokens as $value) {
	if (is_string($value)) {
		//var_dump($value);
		$stripped_source .= "{$value}";
		continue;
	}
	switch ($value[0]) {
		case T_DOC_COMMENT:
		case T_COMMENT:
			break;
		default:
			$stripped_source .= "{$value[1]}";
			break;
	}
}
file_put_contents("$compileFile.tmp", $stripped_source);
`cat build/header.txt > $compileFile`;
`cat $compileFile.tmp |sed 's/^<?php//g'>>$compileFile`;
unlink("$compileFile.tmp");

<?php
// Set up our constants
define('SP_PATH', dirname(dirname(__FILE__)));
define('COMPILED', SP_PATH . DIRECTORY_SEPARATOR . 'SimplePie.compiled.php');

function remove_header($contents)
{
	$tokens = token_get_all($contents);
	$stripped_source = '';
	$stripped_doc = false;
	$stripped_open = false;
	foreach ($tokens as $value)
	{
		if (is_string($value))
		{
			$stripped_source .= "{$value}";
			continue;
		}
		switch ($value[0])
		{
			case T_DOC_COMMENT:
				if (!$stripped_doc)
				{
					$stripped_doc = true;
					continue 2;
				}
				break;
			case T_OPEN_TAG:
				if (!$stripped_open)
				{
					$stripped_open = true;
					continue 2;
				}
				break;
		}
		$stripped_source .= "{$value[1]}";
	}

	return $stripped_source;
}

// Start with the header
$compiled = file_get_contents(SP_PATH . '/build/header.txt');
$compiled .= "\n";

// Add the base class
$contents = file_get_contents(SP_PATH . '/SimplePie.php');
$compiled .= remove_header($contents) . "\n";

// Add all the files in the SimplePie directory
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(SP_PATH . '/SimplePie'));
foreach($files as $file_path => $info)
{
	$contents = file_get_contents($file_path);
	$compiled .= remove_header($contents) . "\n";
}

// Strip excess whitespace
$compiled = preg_replace("#\n\n\n+#", "\n\n", $compiled);

// Finally, save
file_put_contents(COMPILED, $compiled);

Remove Unix commands from build tool and replace with PHP native ones.

Also, only remove the beginning PHP open tag and file-level PHPDoc comment. Fixes #152.


<?php namespace Limoncello\Application\Authorization;

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

/**
 * @package Limoncello\Application
 */
class ContextProperties extends RequestProperties
{
    /** Context key */
    const CTX_CONTAINER = self::REQ_LAST + 1;

    /** Context key */
    const CTX_LAST = self::CTX_CONTAINER + 1;
}

<?php namespace Limoncello\Application\Authorization;

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

/**
 * @package Limoncello\Application
 */
class ContextProperties extends RequestProperties
{
    /** Context key */
    const CTX_CONTAINER = self::REQ_LAST + 1;

    /** Context key */
    const CTX_LAST = self::CTX_CONTAINER;
}

Remove unnecessary increment for the last key.


<?php

namespace Frontend\Modules\Profiles\Tests\Engine;

use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;

final class AuthenticationTest extends WebTestCase
{
    /** @var SpoonDatabase */
    private $database;

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

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Frontend');
        }

        $client = self::createClient();
        $this->loadFixtures($client, [LoadProfiles::class]);

        $this->database = FrontendModel::get('database');
    }

    public function testOldSessionCleanUp()
    {
        $this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));

        Authentication::cleanupOldSessions();

        $this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
    }
}

<?php

namespace Frontend\Modules\Profiles\Tests\Engine;

use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;

final class AuthenticationTest extends WebTestCase
{
    /** @var SpoonDatabase */
    private $database;

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

        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Frontend');
        }

        $client = self::createClient();
        $this->loadFixtures($client, [LoadProfiles::class]);

        $this->database = FrontendModel::get('database');
    }

    public function testOldSessionCleanUp()
    {
        $this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));

        Authentication::cleanupOldSessions();

        $this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
    }

    public function testGettingLoginStatusForNonExistingUser()
    {
        $this->assertEquals('invalid', Authentication::getLoginStatus('non@existe.nt', 'wrong'));
    }

    public function testGettingLoginStatusForUserWithWrongPassword()
    {
        $this->assertEquals('invalid', Authentication::getLoginStatus('test-active@fork-cms.com', 'wrong'));
    }

    public function testGettingLoginStatusForActiveUserWithCorrectPassword()
    {
        $this->assertEquals('active', Authentication::getLoginStatus('test-active@fork-cms.com', 'forkcms'));
    }

    public function testGettingLoginStatusForInactiveUserWithCorrectPassword()
    {
        $this->assertEquals('inactive', Authentication::getLoginStatus('test-inactive@fork-cms.com', 'forkcms'));
    }

    public function testGettingLoginStatusForDeletedUserWithCorrectPassword()
    {
        $this->assertEquals('deleted', Authentication::getLoginStatus('test-deleted@fork-cms.com', 'forkcms'));
    }

    public function testGettingLoginStatusForBlockedUserWithCorrectPassword()
    {
        $this->assertEquals('blocked', Authentication::getLoginStatus('test-blocked@fork-cms.com', 'forkcms'));
    }
}

Test getting the login status of a profile


#Laravel IRC Chat

Search the chat logs to see if your question has already been answered. You can use your own IRC client at Freenode.net in #Laravel.

    Laracon Europe is a two-day event in historic Amsterdam where you'll meet many members of the Laravel community and listen to engaging presentations about the art of software engineering and more.

#Laravel IRC Chat

Search the chat logs to see if your question has already been answered. You can use your own IRC client at Freenode.net in #Laravel.

Channel Moderators are: TaylorOtwell, ShawnMcCool, PhillSparks, daylerees, JasonLewis and JesseOBrien.

    Laracon Europe is a two-day event in historic Amsterdam where you'll meet many members of the Laravel community and listen to engaging presentations about the art of software engineering and more.

Add list of channel moderators for irc page

Signed-off-by: Dries Vints <9818b0f8e34f57ac0059d0bc440479771e319166@gmail.com>


<?php

namespace App\Auth;

use Prob\Handler\ProcInterface;

abstract class PermissionManager
{
    abstract public function __construct(array $settings = []);

    /**
     * @return array|null
     */
    abstract public function getRolesByOperation($operation);

    /**
     * @return bool
     */
    public function hasAllowedRole($accountId, $operation)
    {
        $operationAllowedRoles = $this->getRolesByOperation($operation);
        $accountRoles = AuthManager::getAccountManager()->getRole($accountId) ?: [];

        if ($operationAllowedRoles === null) {
            return AuthManager::isDefaultAllow();
        }

        foreach ($accountRoles as $role) {
            if (in_array($role, $operationAllowedRoles) === true) {
                return true;
            }
        }

        return false;
    }
}

<?php

namespace App\Auth;

abstract class PermissionManager
{
    abstract public function __construct(array $settings = []);

    /**
     * @return array|null
     */
    abstract public function getRolesByOperation($operation);

    /**
     * @return bool
     */
    public function hasAllowedRole($accountId, $operation)
    {
        $operationAllowedRoles = $this->getRolesByOperation($operation);
        $accountRoles = AuthManager::getAccountManager()->getRole($accountId) ?: [];

        if ($operationAllowedRoles === null) {
            return AuthManager::isDefaultAllow();
        }

        foreach ($accountRoles as $role) {
            if (in_array($role, $operationAllowedRoles) === true) {
                return true;
            }
        }

        return false;
    }
}

Remove a not using import stantment

Remove a not using import stantment


<?php

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\View;
use Orchestra\Support\Facades\Asset;
use Orchestra\Support\Facades\Widget;

Event::listen('orchestra.ready: admin', 'Orchestra\Story\Services\Event\DashboardHandler@onDashboardView');
Event::listen('orchestra.form: extension.orchestra/story', 'Orchestra\Story\Services\Event\ExtensionHandler@onFormView');
Event::listen('orchestra.form: extension.orchestra/story', function ()
{
	$placeholder = Widget::make('placeholder.orchestra.extensions');
	$placeholder->add('permalink')->value(View::make('orchestra/story::widgets.help'));
});

Event::listen('orchestra.validate: extension.orchestra/story', function (& $rules)
{
	$rules['page_permalink'] = array('required');
});

Event::listen('orchestra.story.editor: markdown', function ()
{
	$asset = Asset::container('orchestra/foundation::footer');
	$asset->script('editor', 'packages/orchestra/story/vendor/editor/editor.js');
	$asset->style('editor', 'packages/orchestra/story/vendor/editor/editor.css');
	$asset->script('storycms', 'packages/orchestra/story/js/storycms.min.js');
	$asset->script('storycms.md', 'packages/orchestra/story/js/storycms.markdown.min.js', array('editor'));
});

<?php

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\View;
use Orchestra\Support\Facades\Asset;
use Orchestra\Support\Facades\Widget;

Event::listen('orchestra.ready: admin', 'Orchestra\Story\Services\Event\DashboardHandler@onDashboardView');
Event::listen('orchestra.form: extension.orchestra/story', 'Orchestra\Story\Services\Event\ExtensionHandler@onFormView');
Event::listen('orchestra.form: extension.orchestra/story', function ()
{
	$placeholder = Widget::make('placeholder.orchestra.extensions');
	$placeholder->add('permalink')->value(View::make('orchestra/story::widgets.help'));
});

Event::listen('orchestra.validate: extension.orchestra/story', function (& $rules)
{
	$rules['page_permalink'] = array('required');
	$rules['post_permalink'] = array('required');
});

Event::listen('orchestra.story.editor: markdown', function ()
{
	$asset = Asset::container('orchestra/foundation::footer');
	$asset->script('editor', 'packages/orchestra/story/vendor/editor/editor.js');
	$asset->style('editor', 'packages/orchestra/story/vendor/editor/editor.css');
	$asset->script('storycms', 'packages/orchestra/story/js/storycms.min.js');
	$asset->script('storycms.md', 'packages/orchestra/story/js/storycms.markdown.min.js', array('editor'));
});

Add validation for configuring story.

Add validation for configuring story.

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


<?php

namespace EE\Model;
use EE;

/**
 * Site model class.
 */
class Site extends Base {

	/**
	 * @var string Table of the model from where it will be stored/retrived
	 */
	protected static $table = 'sites';

	/**
	 * @var string Primary/Unique key of the table
	 */
	protected static $primary_key = 'site_url';

	/**
	 * Saves current model into database
	 *
	 * @throws \Exception
	 *
	 * @return bool Model saved successfully
	 */
	public function save() {
		$fields = array_merge( $this->fields, [
			'modified_on' => date( 'Y-m-d H:i:s' ),
		] );

		$primary_key_column = static::$primary_key;

		return EE::db()
			->table( static::$table )
			->where( $primary_key_column, $this->$primary_key_column )
			->update( $fields );
	}
}

<?php

namespace EE\Model;
use EE;

/**
 * Site model class.
 */
class Site extends Base {

	/**
	 * @var string Table of the model from where it will be stored/retrived
	 */
	protected static $table = 'sites';

	/**
	 * @var string Primary/Unique key of the table
	 */
	protected static $primary_key = 'site_url';

	/**
	 * Saves current model into database
	 *
	 * @throws \Exception
	 *
	 * @return bool Model saved successfully
	 */
	public function save() {
		$fields = array_merge( $this->fields, [
			'modified_on' => date( 'Y-m-d H:i:s' ),
		] );

		$primary_key_column = static::$primary_key;

		return EE::db()
			->table( static::$table )
			->where( $primary_key_column, $this->$primary_key_column )
			->update( $fields );
	}

	/**
	 * Returns if site is enabled
	 *
	 * @param string $site_url Name of site to check
	 *
	 * @throws \Exception
	 *
	 * @return bool Site enabled
	 */
	public static function enabled( string $site_url ) : bool {
		$site = static::find( $site_url, [ 'site_enabled' ] );

		if ( $site && $site->site_enabled ) {
			return true;
		}
		return false;
	}
}

Add enabled() static function to check if site is enabled

Signed-off-by: Kirtan Gajjar <dda7ffca0822762c3fa90dba716be1cac57d994e@gmail.com>


<?php
class NocaptchaProtector implements SpamProtector {
    /**
     * Return the Field that we will use in this protector
     * @return string
     */
    public function getFormField($name="Recaptcha2Field", $title='Captcha', $value=null) {
        return new NocaptchaField($name, $title);
    }

    /**
     * Not used by Nocaptcha
     */
    public function setFieldMapping($fieldMapping) {}
}
?>

<?php
class NocaptchaProtector implements SpamProtector {
    /**
     * Return the Field that we will use in this protector
     * @return string
     */
    public function getFormField($name="Recaptcha2Field", $title='Captcha', $value=null) {
        return NocaptchaField::create($name, $title);
    }

    /**
     * Not used by Nocaptcha
     */
    public function setFieldMapping($fieldMapping) {}
}
?>

Make NocaptchaField extendable by injector


<?php
/**
 * Slim Framework (https://slimframework.com)
 *
 * @link      https://github.com/slimphp/Slim
 * @copyright Copyright (c) 2011-2017 Josh Lockhart
 * @license   https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
 */
namespace Slim\Tests\Mocks;

use Slim\Http\Message;

/**
 * Mock object for Slim\Http\MessageTest
 */
class MessageStub extends Message
{
    /**
     * Protocol version
     *
     * @var string
     */
    public $protocolVersion;

    /**
     * Headers
     *
     * @var \Slim\Interfaces\Http\HeadersInterface
     */
    public $headers;

    /**
     * Body object
     *
     * @var \Psr\Http\Message\StreamInterface
     */
    public $body;
}

<?php
/**
 * Slim Framework (https://slimframework.com)
 *
 * @link      https://github.com/slimphp/Slim
 * @copyright Copyright (c) 2011-2017 Josh Lockhart
 * @license   https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
 */
namespace Slim\Tests\Mocks;

use Slim\Http\Message;

/**
 * Mock object for Slim\Http\MessageTest
 */
class MessageStub extends Message
{
    /**
     * Protocol version
     *
     * @var string
     */
    public $protocolVersion;

    /**
     * Headers
     *
     * @var \Slim\Http\HeadersInterface
     */
    public $headers;

    /**
     * Body object
     *
     * @var \Psr\Http\Message\StreamInterface
     */
    public $body;
}

Update dock block for new location of HeadersInterface


<?php

namespace MartiAdrogue\SqlBuilder\Test;

use MartiAdrogue\SqlBuilder\SelectBuilder;
use MartiAdrogue\SqlBuilder\Exception\InvalidSqlSyntaxException;

class SelectBuilderTest extends \PHPUnit_Framework_TestCase
{
    private $selectBuilder;

    public function setUp()
    {
        $this->selectBuilder = new SelectBuilder();
    }

    /**
     * @test
     * Test that true does in fact equal true
     */
    public function shouldReturnASelectStatementAccordingWithSQL92Standard()
    {
        $selectSyntax = '/SELECT\s.*[^,]$/';
        $sqlSelect = $this->selectBuilder->select(['row1','row2','row3','row4','row5']);

        $this->assertRegExp(
            $selectSyntax,
            $sqlSelect->__toString(),
            'An statement SQL Select must have the specified sintax from the SQL-92 standard.'
        );
    }

    /**
     * @test
     */
    public function shouldStopFlowWhenReservedWordIsUsedInASqlStatement()
    {
        $this->setExpectedException(InvalidSqlSyntaxException::class);
        $this->selectBuilder->select(['row1','row2','row3','repeat','row5']);
    }
}

<?php

namespace MartiAdrogue\SqlBuilder\Test;

use MartiAdrogue\SqlBuilder\SelectBuilder;
use MartiAdrogue\SqlBuilder\FromBuilder;
use MartiAdrogue\SqlBuilder\Exception\InvalidSqlSyntaxException;

class SelectBuilderTest extends \PHPUnit_Framework_TestCase
{
    private $selectBuilder;

    public function setUp()
    {
        $this->selectBuilder = new SelectBuilder();
    }

    /**
     * @test
     * Test that true does in fact equal true
     */
    public function shouldReturnASelectStatementAccordingWithSQL92Standard()
    {
        $selectSyntax = '/SELECT\s.*[^,]$/';
        $sqlSelect = $this->selectBuilder->select(['row1','row2','row3','row4','row5']);

        $this->assertRegExp(
            $selectSyntax,
            $sqlSelect->__toString(),
            'An statement SQL Select must have the specified sintax from the SQL-92 standard.'
        );
    }

    /**
     * @test
     */
    public function shouldStopFlowWhenReservedWordIsUsedInASqlStatement()
    {
        $this->setExpectedException(InvalidSqlSyntaxException::class);
        $this->selectBuilder->select(['row1','row2','row3','repeat','row5']);
    }

    /**
     * @test
     */
    public function shouldChangeStateOfSelectAndReturnFromStaementObject()
    {
        $sqlSelect = $this->selectBuilder->select(['row1','row2','row3','row4','row5']);
        $this->assertInstanceOf(
            FromBuilder::class,
            $sqlSelect,
            'On change the SelectBuilder It must return an instance of the next Builder, FromBuilder.'
        );
    }
}

Test case to check returned Object

Test case to check returned Object


<?php
namespace UpCloo\App;

class BootTest extends \PHPUnit_Framework_TestCase
{
    public function testGetEmptyServiceManagerOnMissingConfiguration()
    {
        $boot = new Boot(new Config\ArrayProcessor());
        $boot->bootstrap();
        $this->assertInstanceOf("Zend\\ServiceManager\\ServiceManager", $boot->services());
        $this->assertInstanceOf("Zend\\EventManager\\EventManager", $boot->events());
    }

    public function testConfigurationOverwrite()
    {
        $processor = new Config\ArrayProcessor();
        $myConf = [
            "services" => [
                "invokables" => [
                    "UpCloo\\Listener\\Renderer\\Json" => "UpCloo\\Listener\\Renderer\\Json"
                ],
                "aliases" => [
                    "renderer" => "UpCloo\\Listener\\Renderer\\Json",
                ]
            ]
        ];
        $processor->appendConfig($myConf);

        $boot = new Boot($processor);
        $boot->bootstrap();

        $renderer = $boot->services()->get("renderer");

        $this->assertInstanceOf("UpCloo\\Listener\\Renderer\\Json", $renderer);
    }

    public function testServiceManagerIsNotReplaced()
    {
        $boot = new Boot(new Config\ArrayProcessor());

        $serviceManager = new \Zend\ServiceManager\ServiceManager();
        $boot->setServiceManager($serviceManager);

        $boot->bootstrap();

        $this->assertSame($serviceManager, $boot->services());
    }
}

<?php
namespace UpCloo\App;

class BootTest extends \PHPUnit_Framework_TestCase
{
    public function testGetEmptyServiceManagerOnMissingConfiguration()
    {
        $boot = new Boot(new Config\ArrayProcessor());
        $boot->bootstrap();
        $this->assertInstanceOf("Zend\\ServiceManager\\ServiceManager", $boot->services());
        $this->assertInstanceOf("Zend\\EventManager\\EventManager", $boot->events());
    }

    public function testConfigurationOverwrite()
    {
        $processor = new Config\ArrayProcessor();
        $myConf = [
            "services" => [
                "invokables" => [
                    "UpCloo\\Listener\\Renderer\\Json" => "UpCloo\\Listener\\Renderer\\Json"
                ],
                "aliases" => [
                    "renderer" => "UpCloo\\Listener\\Renderer\\Json",
                ]
            ]
        ];
        $processor->appendConfig($myConf);

        $boot = new Boot($processor);
        $boot->bootstrap();

        $renderer = $boot->services()->get("renderer");

        $this->assertInstanceOf("UpCloo\\Listener\\Renderer\\Json", $renderer);
    }

    public function testServiceManagerIsNotReplaced()
    {
        $boot = new Boot(new Config\ArrayProcessor());

        $serviceManager = new \Zend\ServiceManager\ServiceManager();
        $boot->setServiceManager($serviceManager);

        $boot->bootstrap();

        $this->assertSame($serviceManager, $boot->services());
    }

    public function testEventManagerIsNotReplaced()
    {
        $boot = new Boot(new Config\ArrayProcessor());

        $eventManager = new \Zend\EventManager\EventManager();
        $boot->setEventManager($eventManager);

        $boot->bootstrap();

        $this->assertSame($eventManager, $boot->events());
    }
}

Test that the event manager is not replaced


<?php

namespace App\Http\Controllers\All;

use App\Http\Controllers\Controller;
use App\Models\User;
use EtuUTT;
use Request;
use Config;
use View;
use Crypt;
use Redirect;
use Auth;
use Response;

class AuthController extends Controller
{
    /**
     * Show the authentication for newcomer page
     *
     * @return Response
     */
    public function login()
    {
        return View::make('newcomer.login');
    }

    /**
     * Authenticate the newcomer
     *
     * @return Response
     */
    public function loginSubmit()
    {
        $user = User::where('login', Request::get('login'))->get()->first();
        if ($user && !empty($user->password)) {
            if (password_verify(Request::get('password'), $user->password)) {
                Auth::login($user, true);
                if ($user->isNewcomer()) {
                    return Redirect::route('newcomer.home')->withSuccess('Vous êtes maintenant connecté.');
                }
                else {
                    return Redirect::route('menu')->withSuccess('Vous êtes maintenant connecté.');
                }
            }
        }
        return $this->error('Identifiant ou mot de passe incorrect. Contactez integration@utt.fr si vous n\'arrivez pas à vous connecter.');
    }

    /**
     * log out the newcomer
     *
     * @return Response
     */
    public function logout()
    {
        Auth::logout();
        return Redirect::route('index')->withSuccess('Vous êtes maintenant déconnecté.');
    }
}

<?php

namespace App\Http\Controllers\All;

use App\Http\Controllers\Controller;
use App\Models\User;
use EtuUTT;
use Request;
use Config;
use View;
use Crypt;
use Redirect;
use Auth;
use Response;

class AuthController extends Controller
{
    /**
     * Show the authentication for newcomer page
     *
     * @return Response
     */
    public function login()
    {
        return View::make('newcomer.login');
    }

    /**
     * Authenticate the newcomer
     *
     * @return Response
     */
    public function loginSubmit()
    {
        $user = User::where('login', Request::get('login'))->get()->first();
        if ($user && !empty($user->password)) {
            if (password_verify(Request::get('password'), $user->password)) {
                $user->last_login = new \DateTime();
                $user->save();
                Auth::login($user, true);
                if ($user->isNewcomer()) {
                    return Redirect::route('newcomer.home')->withSuccess('Vous êtes maintenant connecté.');
                }
                else {
                    return Redirect::route('menu')->withSuccess('Vous êtes maintenant connecté.');
                }
            }
        }
        return $this->error('Identifiant ou mot de passe incorrect. Contactez integration@utt.fr si vous n\'arrivez pas à vous connecter.');
    }

    /**
     * log out the newcomer
     *
     * @return Response
     */
    public function logout()
    {
        Auth::logout();
        return Redirect::route('index')->withSuccess('Vous êtes maintenant déconnecté.');
    }
}

Update last login time on newcomer auth

Update last login time on newcomer auth


<?php
/**
 * This file is part of the Tmdb package.
 *
 * (c) Vincent Faliès <vincent.falies@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *

 * @author Vincent Faliès <vincent.falies@gmail.com>
 * @copyright Copyright (c) 2017
 */

namespace vfalies\tmdb\Interfaces\Results;

/**
 * Interface for People Results type object
 * @package Tmdb
 * @author Vincent Faliès <vincent.falies@gmail.com>
 * @copyright Copyright (c) 2017
 */
interface PeopleResultsInterface extends ResultsInterface
{
    /**
     * Profile path
     */
    public function getProfilePath();

    /**
     * Adult
     */
    public function getAdult();

    /**
     * People known for
     */
    public function getKnownFor();

    /**
     * People name
     */
    public function getName();

    /**
     * People popularity
     */
    public function getPopularity();
}

<?php
/**
 * This file is part of the Tmdb package.
 *
 * (c) Vincent Faliès <vincent.falies@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *

 * @author Vincent Faliès <vincent.falies@gmail.com>
 * @copyright Copyright (c) 2017
 */

namespace vfalies\tmdb\Interfaces\Results;

/**
 * Interface for People Results type object
 * @package Tmdb
 * @author Vincent Faliès <vincent.falies@gmail.com>
 * @copyright Copyright (c) 2017
 */
interface PeopleResultsInterface extends ResultsInterface
{
    /**
     * Profile path
     */
    public function getProfilePath();

    /**
     * Adult
     */
    public function getAdult();

    /**
     * People name
     */
    public function getName();

    /**
     * People popularity
     */
    public function getPopularity();
}

Remove useless method in interface

Remove useless method in interface


<?
include '../scat.php';

$name= $_REQUEST['name'];
if (empty($name))
  die_jsonp("You need to supply at least a name.");

$q= "SELECT id
       FROM person
      WHERE name = '" . $db->real_escape_string($name) . "'";
$r= $db->query($q)
  or die_query($db, $q);

if ($r->num_rows)
  die_jsonp("Someone by that name already exists.");

$list= array();
foreach(array('name', 'company', 'address',
              'email', 'phone', 'tax_id') as $field) {
  $list[]= "$field = '" . $db->real_escape_string($_REQUEST[$field]) . "', ";
}

$fields= join('', $list);

// add payment record
$q= "INSERT INTO person
        SET $fields
        active = 1";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('person' => $db->insert_id));

<?
include '../scat.php';

$name= $_REQUEST['name'];
$company= $_REQUEST['company'];
if (empty($name) && empty($company))
  die_jsonp("You need to supply at least a name or company.");

if ($name) {
  $q= "SELECT id
         FROM person
        WHERE name = '" . $db->escape($name) . "'";
  $r= $db->query($q)
    or die_query($db, $q);

  if ($r->num_rows)
    die_jsonp("Someone by that name already exists.");
}

$list= array();
foreach(array('name', 'company', 'address',
              'email', 'phone', 'tax_id') as $field) {
  $list[]= "$field = '" . $db->real_escape_string($_REQUEST[$field]) . "', ";
}

$fields= join('', $list);

// add payment record
$q= "INSERT INTO person
        SET $fields
        active = 1";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('person' => $db->insert_id));

Allow adding a person that is just a company


<!DOCTYPE html>

        <title>EndofCodes Demo</title>
        <?php
            include 'helpers/html.php';
            includeStyle( "general" );
            includeStyle( "header" );
            includeStyle( "home" );
            includeStyle( "register" );
            includeStyle( "login" );
        ?>
        <meta
            http-equiv="Content-type"
            content="text/html; charset=utf-8" />

Endofcodes

Rules

                <?php
                    if ( isset( $_SESSION[ 'user' ]['username' ] ) ) {
                        ?>
<a href="index.php?resource=user&method=view&username=<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?>">Profile
<?php
                    }
                ?>

Blog

                <?php
                    if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
                        ?>
<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?><select>
                            <option> </option>
                            <option value="logout">Logout</option>
                        </select>
<?php
                    }
                    else {
                        ?>
Login
<?php
                    }
                ?>

<!DOCTYPE html>

        <title>EndofCodes Demo</title>
        <?php
            include 'helpers/html.php';
            includeStyle( "general" );
            includeStyle( "header" );
            includeStyle( "home" );
            includeStyle( "register" );
            includeStyle( "login" );
        ?>
        <meta charset="utf-8">

Endofcodes

Rules

                <?php
                    if ( isset( $_SESSION[ 'user' ]['username' ] ) ) {
                        ?>
<a href="index.php?resource=user&method=view&username=<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?>">Profile
<?php
                    }
                ?>

Blog

                <?php
                    if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
                        ?>
<?php
                            echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
                        ?><select>
                            <option> </option>
                            <option value="logout">Logout</option>
                        </select>
<?php
                    }
                    else {
                        ?>
Login
<?php
                    }
                ?>

Use HTML5 utf8 meta tag

Use HTML5 utf8 meta tag


<?

include('../EpiDBClient.php');

$client = new EpiDBClient();
$client->submit('{ "source": "php" }');

<?

require_once('../EpiDBClient.php');

$client = new EpiDBClient();
$client->submit('{ "source": "php" }');

Use require_once() instead of include()

Use require_once() instead of include()


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return redirect('/api/documentation');
});

Change root redirect to API docs

Change root redirect to API docs


<?php

// Prevent this class from being included if another plugin
// has already loaded it
if (class_exists('GSUtils')) return;

class GSUtils {
  // ...
}

<?php

// Prevent this class from being included if another plugin
// has already loaded it
if (class_exists('GSUtils')) return;

class GSUtils {
  // == CONSTANTS ==
  const EXCEPTION_MKDIR = 'mkDirErr';
  const EXCEPTION_MKFILE = 'mkFileErr';

  // == PROPERTIES ==
  protected $options;
  protected $defaults = array(
    'htaccess' => 'Deny from all',
  );

  // == METHODS ==
  // Constructor
  public function __construct($options = array()) {
    $this->options = array_merge(array(
      'basepath' => GSDATAOTHERPATH,
    ), $options);
  }

  // Get a path (from the basepath)
  public function path($path = null) {
    if (strpos($path, $this->options['basepath']) !== 0) {
      $path = $this->options['basepath'] . $path;
    }
    return $path;
  }

  // Get file info
  public function fileinfo($file) {
    $file = $this->path($file);
    $info = pathinfo($file);
    $info = array_merge(array(
      'extension' => false,
    ), $info);

    return $info;
  }

  // Make a directory
  public function mkdir($path, $htaccess = true, $mode = 0755) {
    $path = $this->path($path);
    $mkdir = file_exists($path) || @mkdir($path, $mode, $recursive = true);
    if ($mkdir) {
      if ($htaccess === true) {
        $htaccess = $this->defaults['htaccess'];
      }

      if ($htaccess) {
        return $this->mkfile($path . '/.htaccess', $htaccess);
      } else {
        return $mkdir;
      }
    } else {
      throw new Exception(static::EXCEPTION_MKDIR);
    }
  }

  // Make a file
  public function mkfile($file, $data) {
    $file = $this->path($file);
    $info = $this->fileinfo($file);

    if ($info['extension'] == 'json') {
      $json = json_encode($data);
      $mkfile = @file_put_contents($file, $json);
    } elseif ($info['extension'] == 'xml') {
      // TODO
      $mkfile = false;
    } else {
      $mkfile = @file_put_contents($file, $data);
    }

    if ($mkfile) {
      return $mkfile;
    } else {
      throw new Exception(static::EXCEPTION_MKFILE);
    }
  }
}

Implement some methods Constructor, mkdir, mkfile, path


<?php /**
 * Created by PhpStorm.
 * User: Philipp Dippel
 * Date: 31.05.17
 * Time: 17:44
 */

?>

<div id="mainContainer">
    <canvas id="mainCanvas" width="2000" height="2000"></canvas>
</div>

<script type="text/javascript">

    $('document').ready(function ()
    {
            $.getScript("widgets/Analoguhr/ClockStylekit.js")
                .done(function (script, textStatus)
                {
                    clock();
                })
                .fail(function (jqxhr, settings, exception)
                {
                    console.error("Failed to load ClockStylekit");
                    cosnole.error(exception);
                });
    });

</script>

<?php /**
 * Created by PhpStorm.
 * User: Philipp Dippel
 * Date: 31.05.17
 * Time: 17:44
 */

?>

<div id="mainContainer">
    <canvas id="mainCanvas" width="2000" height="2000"></canvas>
</div>

<script type="text/javascript">

    $('document').ready(function ()
    {
            $.getScript("widgets/Analoguhr/ClockStyleKit.js")
                .done(function (script, textStatus)
                {
                    clock();
                })
                .fail(function (jqxhr, settings, exception)
                {
                    console.error("Failed to load ClockStyleKit");
                    console.error(exception);
                });
    });

</script>

Add fix for analog watch

Add fix for analog watch


<?php

namespace ampf\skeleton\beanAccess\repos;

use \ampf\skeleton\doctrine\repositories\Test;

trait Test
{
	protected $__testRepository = null;

	/**
	 * @return Test
	 */
	public function getTestRepository()
	{
		if ($this->__testRepository === null)
		{
			$this->setTestRepository(
				$this->getBeanFactory()->get(
					'Doctrine.Repository.Test',
					function(\ampf\beans\BeanFactory $beanFactory, array &$beanConfig) {
						return $beanFactory
							->get('EntityManagerFactory')
							->get()
							->getRepository('\ampf\skeleton\doctrine\entities\Test');
					}
				)
			);
		}
		return $this->__testRepository;
	}

	/**
	 * @param Test $testRepository
	 */
	public function setTestRepository(Test $testRepository)
	{
		$this->__testRepository = $testRepository;
	}
}

<?php

namespace ampf\skeleton\beanAccess\repos;

use \ampf\skeleton\doctrine\repositories\Test;

trait Test
{
	protected $__testRepository = null;

	/**
	 * @return Test
	 */
	public function getTestRepository()
	{
		if ($this->__testRepository === null)
		{
			$this->setTestRepository(
				$this->getBeanFactory()->get(
					'Doctrine.Repository.Test',
					function(\ampf\beans\BeanFactory $beanFactory, array &$beanConfig) {
						return $beanFactory
							->get('EntityManagerFactory')
							->get()
							->getRepository('\ampf\skeleton\doctrine\entities\Test');
					}
				)
			);
		}
		return $this->__testRepository;
	}

	/**
	 * @param Test $testRepository
	 */
	public function setTestRepository(Test $testRepository)
	{
		$this->__testRepository = $testRepository;
	}

	/**
	 * @return \ampf\beans\BeanFactory
	 */
	abstract public function getBeanFactory();
}

Make sure getBeanFactory() is available in access traits.


<?php

/**
 * Minds S3 Torrent Builder
 *
 * @author emi
 */

namespace Minds\Core\Torrent\TorrentBuilders;

use Minds\Core\Di\Di;
use Minds\Core\Media\Services\AWS;

class S3 implements TorrentBuilderInterface
{
    /** @var AWS */
    protected $aws;

    /** @var string */
    protected $key;

    /** @var string */
    protected $file;

    public function __construct($aws = null)
    {
        $this->aws = $aws ?: new AWS([
            's3' => [
                'endpoint' => Di::_()->get('Config')->get('cinemr_url'),
                'force_path_style' => true,
                'bucket_endpoint' => true,
            ]
        ]);
    }

    /**
     * @param $key
     * @return $this
     */
    public function setKey($key)
    {
        $this->key = $key;
        return $this;
    }

    /**
     * @param mixed $file
     * @return S3
     */
    public function setFile($file)
    {
        $this->file = $file;
        return $this;
    }

    /**
     * Downloads a pre-built torrent from a cinemr S3 object
     * @return bool|string
     */
    public function build()
    {
        $this->aws->setKey($this->key);
        return $this->aws->getTorrent($this->file);
    }
}

<?php

/**
 * Minds S3 Torrent Builder
 *
 * @author emi
 */

namespace Minds\Core\Torrent\TorrentBuilders;

use Minds\Core\Di\Di;
use Minds\Core\Media\Services\AWS;
use Minds\Core\Media\Services\Factory;

class S3 implements TorrentBuilderInterface
{
    /** @var AWS */
    protected $aws;

    /** @var string */
    protected $key;

    /** @var string */
    protected $file;

    public function __construct($aws = null)
    {
        $this->aws = $aws ?: Factory::build('AWS');
    }

    /**
     * @param $key
     * @return $this
     */
    public function setKey($key)
    {
        $this->key = $key;
        return $this;
    }

    /**
     * @param mixed $file
     * @return S3
     */
    public function setFile($file)
    {
        $this->file = $file;
        return $this;
    }

    /**
     * Downloads a pre-built torrent from a cinemr S3 object
     * @return bool|string
     */
    public function build()
    {
        $this->aws->setKey($this->key);
        return $this->aws->getTorrent($this->file);
    }
}

(fix): Allow using roles and default AWS config


<?php
namespace Tenet\Filter;

abstract class AbstractAssociationFilter
{
	/**
	 * @todo refactor this... it can be better for scalar vs array
	 * @todo rename the object var in the checks
	 */
	protected function makeObject($accessor, $object, $target, $data)
	{
		$manager     = $accessor->getObjectManager();
		$metadata    = $manager->getClassMetadata($target);
		$identifiers = $metadata->getIdentifierFieldNames($object);

		// handle object of type target
		if ($data instanceof $target) {
			return $data;
		}

		// handle scalar identifier
		if (is_scalar($data) && count($identifiers) === 1) {
			return $manager->find($target, $data) ?: new $target;
		}

		// handle keyed identifier(s)
		if (is_array($data)) {
			// get array of identifier data passed in
			$ids = array_filter(array_intersect_key($data, array_flip($identifiers)), function($v) {
				return ($v === '' || $v === null) ? false : true;
			});

			// if all identifiers are present, try to find the object
			if (count($ids) === count($identifiers)) {
				$object = $manager->find($target, $ids) ?: new $target;
				return $accessor->fill($object, $data);
			}
		}

		return new $target;
	}
}

<?php
namespace Tenet\Filter;

abstract class AbstractAssociationFilter
{
	/**
	 * @todo refactor this... it can be better for scalar vs array
	 * @todo rename the object var in the checks
	 */
	protected function makeObject($accessor, $object, $target, $data)
	{
		$manager     = $accessor->getObjectManager();
		$metadata    = $manager->getClassMetadata($target);
		$identifiers = $metadata->getIdentifierFieldNames($object);

		// handle object of type target
		if ($data instanceof $target) {
			return $data;
		}

		// handle scalar identifier
		if (is_scalar($data) && count($identifiers) === 1) {
			return $manager->find($target, $data) ?: new $target;
		}

		$object = new $target;

		// handle keyed identifier(s)
		if (is_array($data)) {
			// get array of identifier data passed in
			$ids = array_filter(array_intersect_key($data, array_flip($identifiers)), function($v) {
				return ($v === '' || $v === null) ? false : true;
			});

			// if all identifiers are present, try to find the object
			if (count($ids) === count($identifiers)) {
				$exiting_record = $manager->find($target, $ids);

				if ($existing_record) {
					$object = $exiting_record;
				}
			}

			$accessor->fill($object, $data);
		}

		return $object;
	}
}

Fix for not filling associated object unless they had ID fields.

If I'm not misunderstanding, the intended behavior is to be able to
populate completely new records as well.  The fill was left inside the
identifier column conditions which meant unless you set them you
couldn't create a new record.


<?php
require_once __DIR__ . '/deployer/recipe/configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';

serverList(__DIR__ . '/stage/servers.yml');
set('repository', '{{repository}}');

set('keep_releases', 2);

set('shared_files', [
    'config/db.php'
]);

task('deploy:build_assets', function () {
   runLocally('gulp build');
   upload(__DIR__ . '/web/css', '{{release_path}}/web/css');
   upload(__DIR__ . '/web/js', '{{release_path}}/web/js');
   upload(__DIR__ . '/web/fonts', '{{release_path}}/web/fonts');
})->desc('Build assets');

after('deploy:shared', 'deploy:configure');
after('deploy:run_migrations', 'deploy:build_assets');

<?php
require_once __DIR__ . '/deployer/recipe/configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';

serverList(__DIR__ . '/stage/servers.yml');
set('repository', '{{repository}}');

if('{{stage}}' === 'local') {
  env('composer_options', 'install --verbose --no-progress --no-interaction');
}

set('keep_releases', 2);

set('shared_files', [
    'config/db.php'
]);

task('deploy:build_assets', function () {
   runLocally('gulp build');
   upload(__DIR__ . '/web/css', '{{release_path}}/web/css');
   upload(__DIR__ . '/web/js', '{{release_path}}/web/js');
   upload(__DIR__ . '/web/fonts', '{{release_path}}/web/fonts');
})->desc('Build assets');

after('deploy:shared', 'deploy:configure');
after('deploy:run_migrations', 'deploy:build_assets');

Install Composer dev deps in local stage


<?php
namespace Onion\Framework\Middleware\Internal;

use Interop\Http\Middleware\ServerMiddlewareInterface;
use Interop\Http\Middleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Request\Uri;

class ModulePathStripperMiddleware implements ServerMiddlewareInterface
{
    private $routePathPrefix;

    public function __construct($prefix)
    {
        $this->routePathPrefix = $prefix;
    }

    public function process(Request $request, DelegateInterface $delegate): ResponseInterface
    {
        $path = $request->getUri()->getPath();

        return $delegate->process(
            $request->withUri(
                $request->getUri()->withPath(
                    '/' . ltrim(substr($path, strlen($this->routePathPrefix)). '/')
                )
            )
        );
    }
}

<?php
namespace Onion\Framework\Middleware\Internal;

use Interop\Http\Middleware\ServerMiddlewareInterface;
use Interop\Http\Middleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Request\Uri;

class ModulePathStripperMiddleware implements ServerMiddlewareInterface
{
    private $routePathPrefix;

    public function __construct($prefix)
    {
        $this->routePathPrefix = $prefix;
    }

    public function process(Request $request, DelegateInterface $delegate): ResponseInterface
    {
        $path = $request->getUri()->getPath();

        return $delegate->process(
            $request->withUri(
                $request->getUri()->withPath(
                    '/' . ltrim(substr($path, strlen($this->routePathPrefix)), '/')
                )
            )
        );
    }
}

Fix misplaced dot, causing issues with routing


<?php
namespace Apitude\Core\Template;

use Apitude\Core\Provider\AbstractServiceProvider;
use Apitude\Core\Utility\Arr;
use Handlebars\Handlebars;
use Handlebars\Loader\FilesystemLoader;
use Silex\Application;

class TemplateServiceProvider extends AbstractServiceProvider
{
    public function register(Application $app)
    {
        parent::register($app);
        $config = $app['config'];

        $templatePathConfigPath = 'template.handlebars.path';
        if (! Arr::path($config, $templatePathConfigPath)) {
            Arr::setPath(
                $config,
                $templatePathConfigPath,
                APP_PATH . '/templates'
            );
        }
        $app['handlebars'] = $app->share(function ($app) {
            return new Handlebars([
                'loader' => new FilesystemLoader(
                    Arr::path($config, $templatePathConfigPath),
                    [
                        'extension' => '.hbs',
                    ]
                ),
                'partials_loader' => new FilesystemLoader(
                    Arr::path($config, $templatePathConfigPath),
                    [
                        'prefix' => '_',
                    ]
                )
            ]);
        });

        $app['config'] = $config;
    }
}

<?php
namespace Apitude\Core\Template;

use Apitude\Core\Provider\AbstractServiceProvider;
use Apitude\Core\Utility\Arr;
use Handlebars\Handlebars;
use Handlebars\Loader\FilesystemLoader;
use Silex\Application;

class TemplateServiceProvider extends AbstractServiceProvider
{
    public function register(Application $app)
    {
        parent::register($app);
        $config = $app['config'];

        $app['handlebars'] = $app->share(function ($app) {
            $templatePathConfigPath = 'template.handlebars.path';
            if (! Arr::path($config, $templatePathConfigPath)) {
                Arr::setPath(
                    $config,
                    $templatePathConfigPath,
                    APP_PATH . '/templates'
                );
            }

            return new Handlebars([
                'loader' => new FilesystemLoader(
                    Arr::path($config, $templatePathConfigPath),
                    [
                        'extension' => '.hbs',
                    ]
                ),
                'partials_loader' => new FilesystemLoader(
                    Arr::path($config, $templatePathConfigPath),
                    [
                        'prefix' => '_',
                    ]
                )
            ]);
        });

        $app['config'] = $config;
    }
}

Define template path inside share callback


<table {!! $attributes !!}>
    <colgroup>
        @foreach ($columns as $column)
            <col width="{!! $column->getWidth() !!}" />
        @endforeach
    </colgroup>
    @yield('table.header')
    <thead>
    <tr>
        @foreach ($columns as $column)
            <th {!! $column->getHeader()->htmlAttributesToString() !!}>
                {!! $column->getHeader()->render() !!}
            </th>
        @endforeach
    </tr>
    </thead>
    @yield('table.footer')
</table>

<table {!! $attributes !!}>
    <colgroup>
        @foreach ($columns as $column)
            <col width="{!! $column->getWidth() !!}" />
        @endforeach
    </colgroup>
    <thead>
    @yield('table.header')
    </thead>
    <thead>
    <tr>
        @foreach ($columns as $column)
            <th {!! $column->getHeader()->htmlAttributesToString() !!}>
                {!! $column->getHeader()->render() !!}
            </th>
        @endforeach
    </tr>
    </thead>
    @yield('table.footer')
</table>

Fix for filters sorting position

Fix for filters sorting position

Again fixed.... boooring.


<?php

namespace Alexpechkarev\GoogleGeocoder;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;

class GoogleGeocoderServiceProvider extends ServiceProvider {

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        AliasLoader::getInstance()->alias('Geocoder','Alexpechkarev\GoogleGeocoder\Facades\GoogleGeocoderFacade');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['GoogleGeocoder'] = $this->app->share(function($app)
        {
            $config = array();
            $config['applicationKey']   = Config::get('google-geocoder.applicationKey');
            $config['requestUrl']       = Config::get('google-geocoder.requestUrl');

            // Throw an error if request URL is empty
            if (empty($config['requestUrl'])) {
                throw new \InvalidArgumentException('Request URL is empty, please check your config file.');
            }

            return new GoogleGeocoder($config);
        });
    }

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

}

<?php

namespace Alexpechkarev\GoogleGeocoder;

use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;

class GoogleGeocoderServiceProvider extends ServiceProvider {

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        AliasLoader::getInstance()->alias('Geocoder','Alexpechkarev\GoogleGeocoder\Facades\GoogleGeocoderFacade');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        #$this->app['GoogleGeocoder'] = $this->app->share(function($app)
        $this->app['GoogleGeocoder'] = $this->app->singleton('GoogleGeocoder', function($app)
        {
            $config = array();
            $config['applicationKey']   = Config::get('google-geocoder.applicationKey');
            $config['requestUrl']       = Config::get('google-geocoder.requestUrl');

            // Throw an error if request URL is empty
            if (empty($config['requestUrl'])) {
                throw new \InvalidArgumentException('Request URL is empty, please check your config file.');
            }

            return new GoogleGeocoder($config);
        });
    }

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

}

Replace deprecated share method with singleton


<?php

$configDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'models' .
    DIRECTORY_SEPARATOR . 'settings' . DIRECTORY_SEPARATOR;
require_once($configDir . 'JsonConfigTrait.php');
require_once($configDir . 'AntragsgruenApp.php');

$config = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'config.json');
$params = new \app\models\settings\AntragsgruenApp($config);
$common = require(__DIR__ . DIRECTORY_SEPARATOR . 'common.php');
unset($common['defaultRoute']);

return yii\helpers\ArrayHelper::merge(
    $common,
    [
        'id'                  => 'basic-console',
        'controllerNamespace' => 'app\commands',
    ]
);

<?php

$configDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'models' .
    DIRECTORY_SEPARATOR . 'settings' . DIRECTORY_SEPARATOR;
require_once($configDir . 'JsonConfigTrait.php');
require_once($configDir . 'AntragsgruenApp.php');

if (isset($_SERVER['ANTRAGSGRUEN_CONFIG'])) {
    $configFile = $_SERVER['ANTRAGSGRUEN_CONFIG'];
} elseif (isset($_ENV['ANTRAGSGRUEN_CONFIG'])) {
    $configFile = $_SERVER['ANTRAGSGRUEN_CONFIG'];
} else {
    $configFile = __DIR__ . DIRECTORY_SEPARATOR . 'config.json';
}

$config = file_get_contents($configFile);
$params = new \app\models\settings\AntragsgruenApp($config);
$common = require(__DIR__ . DIRECTORY_SEPARATOR . 'common.php');
unset($common['defaultRoute']);

return yii\helpers\ArrayHelper::merge(
    $common,
    [
        'id'                  => 'basic-console',
        'controllerNamespace' => 'app\commands',
    ]
);

Fix Updater with custom config.json-locations / allow ANTRAGSGRUEN_CONFIG with ./yii


<?php

namespace Furniture\FactoryBundle\Security\Voter;

use Furniture\UserBundle\Entity\User;
use Furniture\FactoryBundle\Entity\Factory;
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter;

class ViewFactoryVoter extends AbstractVoter
{
    /**
     * {@inheritDoc}
     */
    protected function getSupportedClasses()
    {
        return [Factory::class];
    }

    /**
     * {@inheritDoc}
     */
    protected function getSupportedAttributes()
    {
        return ['ACTIVE_RELATION'];
    }

    /**
     * {@inheritDoc}
     */
    protected function isGranted($attribute, $factory, $user = null)
    {
        /** @var \Furniture\FactoryBundle\Entity\Factory $factory */
        if (!$user || !$user instanceof User) {
            return false;
        }

        switch ($attribute) {
            case 'ACTIVE_RELATION':
                if (!$user->isRetailer()) {
                    return false;
                }

                $factoryRetailerRelation = $factory->getRetailerRelationByRetailer(
                    $user
                        ->getRetailerUserProfile()
                        ->getRetailerProfile()
                );

                if ($factory->isEnabled() && (($factoryRetailerRelation
                            && $factoryRetailerRelation->isActive()
                            && $factoryRetailerRelation->isFactoryAccept())
                        || $factory->getDefaultRelation()->isAccessProducts())
                ) {
                    return true;
                }

                return false;

            default:
                return false;
        }
    }
}

<?php

namespace Furniture\FactoryBundle\Security\Voter;

use Furniture\UserBundle\Entity\User;
use Furniture\FactoryBundle\Entity\Factory;
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter;

class ViewFactoryVoter extends AbstractVoter
{
    /**
     * {@inheritDoc}
     */
    protected function getSupportedClasses()
    {
        return [Factory::class];
    }

    /**
     * {@inheritDoc}
     */
    protected function getSupportedAttributes()
    {
        return ['ACTIVE_RELATION'];
    }

    /**
     * {@inheritDoc}
     */
    protected function isGranted($attribute, $factory, $user = null)
    {
        /** @var \Furniture\FactoryBundle\Entity\Factory $factory */
        if (!$user || !$user instanceof User) {
            return false;
        }

        switch ($attribute) {
            case 'ACTIVE_RELATION':
                if (!$user->isRetailer()) {
                    return false;
                }

                $factoryRetailerRelation = $factory->getRetailerRelationByRetailer(
                    $user
                        ->getRetailerUserProfile()
                        ->getRetailerProfile()
                );

                if ($factory->isEnabled() && (($factoryRetailerRelation
                            && $factoryRetailerRelation->isActive()
                            && $factoryRetailerRelation->isFactoryAccept()
                            && $factoryRetailerRelation->isAccessProducts())
                        || $factory->getDefaultRelation()->isAccessProducts())
                ) {
                    return true;
                }

                return false;

            default:
                return false;
        }
    }
}

Update factory voter ACTIVE_RELATION statement


<?php
namespace Mozilla\Persona\Provider\Laravel;

use Auth;
use Illuminate\Auth\Guard;
use Illuminate\Support\ServiceProvider;
use Mozilla\Persona\Identity;
use Mozilla\Persona\Verifier;
use Request;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('mozilla/persona');
        Auth::extend(
            'persona',
            function () {
                return new Guard(new PersonaUserProvider, $this->app->make('session'));
            }
        );
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(
            'persona.verifier',
            function ($app) {
                $audience = sprintf('%s://%s:%u', Request::getScheme(), Request::getHost(), Request::getPort());
                return new Verifier($audience);
            }
        );
        $this->app->bind(
            'persona.identity',
            function ($app, $assertion) {
                return new Identity($assertion);
            }
        );
        $this->app->bind(
            'persona.user',
            function ($app, $attributes) {
                return new PersonaUser($attributes);
            }
        );
    }

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

<?php
namespace Mozilla\Persona\Provider\Laravel;

use Auth;
use Illuminate\Auth\Guard;
use Illuminate\Support\ServiceProvider;
use Mozilla\Persona\Identity;
use Mozilla\Persona\Verifier;
use Request;

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

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('mozilla/persona');
        Auth::extend(
            'persona',
            function () {
                return new Guard(new PersonaUserProvider, $this->app->make('session'));
            }
        );
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(
            'persona.verifier',
            function ($app, $endpoint) {
                $audience = sprintf('%s://%s:%u', Request::getScheme(), Request::getHost(), Request::getPort());
                return (empty($endpoint)) ? new Verifier($audience) : new Verifier($audience, $endpoint);
            }
        );
        $this->app->bind(
            'persona.identity',
            function ($app, $assertion) {
                return new Identity($assertion);
            }
        );
        $this->app->bind(
            'persona.user',
            function ($app, $attributes) {
                return new PersonaUser($attributes);
            }
        );
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return array('persona.verifier', 'persona.identity', 'persona.user');
    }
}

Allow custom endpoint in persona.verifier.


<?php
/**
 * Payment Secupaycreditcards Api Model class
 */

namespace SecucardConnect\Product\Payment\Model;

/**
 * Payment Secupaycreditcards Api Model class
 *
 */
class SecupayCreditcard extends Transaction
{
    /**
     * @var \SecucardConnect\Product\Payment\Model\Customer
     */
    public $customer;

}

<?php
/**
 * Payment Secupaycreditcards Api Model class
 */

namespace SecucardConnect\Product\Payment\Model;

/**
 * Payment Secupaycreditcards Api Model class
 *
 */
class SecupayCreditcard extends Transaction
{
    /**
     * @var \SecucardConnect\Product\Payment\Model\Customer
     */
    public $customer;

    public $url_success;

    public $url_push;

    public $iframe_url;

}

ADD some special uris for cc payment

ADD some special uris for cc payment