<?php

namespace Psocksd\Command;

use Psocksd\App;

class Help implements CommandInterface
{
    private $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function run($args)
    {
        echo 'psocksd help:' . PHP_EOL;
        foreach ($this->app->getCommands() as $name => $command) {
            echo '  ' . $name . ' - ' . $command->getHelp() . PHP_EOL;
        }
    }

    public function getHelp()
    {
        return 'show this very help';
    }
}

<?php

namespace Psocksd\Command;

use Psocksd\App;

class Help implements CommandInterface
{
    private $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function run($args)
    {
        echo 'psocksd help:' . PHP_EOL;
        $this->dumpCommands($this->app->getCommands());
    }

    public function dumpCommands($commands)
    {
        $help = array();
        foreach ($commands as $name => $command) {
            $help[$name] = $command->getHelp();
        }
        return $this->dumpHelp($help);
    }

    public function dumpHelp($help)
    {
        foreach ($help as $name => $info) {
            echo '    ' . $name . PHP_EOL .
                 '        ' . $info . PHP_EOL;
        }
    }

    public function getHelp()
    {
        return 'show this very help';
    }
}

Change formatting of help output

Change formatting of help output


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

  echo "The POST is $_POST";

  var_dump($_POST);

  $state = $_POST['shippingState'];

  if ( !strcmp("GA", $state) ) {

    // the shipping address is in Georgia, so go ahead

    $token  = $_POST['stripeToken'];
    $email  = $_POST['emailAddress'];

    echo "$token and $email";

    $customer = Stripe_Customer::create(array(
        'email' => $email,
        'card'  => $token
    ));

    $charge = Stripe_Charge::create(array(
        'customer' => $customer->id,
        'amount'   => 1500,
        'currency' => 'usd',
        'description' => 'Widget, Qty 1'
    ));

    echo '
Successfully charged $15.00!
';

  } else {

    echo "Sorry, we can only ship to addresses in GA.";
    echo "Hit the back button and try again with 'GA' in the state field.";

  }

?>

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

  var_dump($_POST);

  $state = $_POST['shippingState'];

  if ( !strcmp("GA", $state) ) {

    // the shipping address is in Georgia, so go ahead

    $token  = $_POST['stripeToken'];
    $email  = $_POST['emailAddress'];

    echo "$token and $email";

    $customer = Stripe_Customer::create(array(
        'email' => $email,
        'card'  => $token
    ));

    $charge = Stripe_Charge::create(array(
        'customer' => $customer->id,
        'amount'   => 1500,
        'currency' => 'usd',
        'description' => 'Widget, Qty 1'
    ));

    echo '
Successfully charged $15.00!
';

  } else {

    echo "Sorry, we can only ship to addresses in GA.";
    echo "Hit the back button and try again with 'GA' in the state field.";

  }

?>

Remove incorrect debugging line, leave var_dump


<?php
if(!isset($_GET['list']))
    die();

$type = $_GET['list'];

if($type !== "white" || $type !== "black")
    die("Invalid list parameter");

$rawList = file_get_contents("/etc/pihole/${type}list.txt");
$list = explode("\n", $rawList);

// Get rid of empty lines
for($i = sizeof($list)-1; $i >= 0; $i--) {
    if($list[$i] == "")
        unset($list[$i]);
}

echo json_encode(array_values($list));

<?php
if(!isset($_GET['list']))
    die();

$type = $_GET['list'];

if($type !== "white" && $type !== "black")
    die("Invalid list parameter");

$rawList = file_get_contents("/etc/pihole/${type}list.txt");
$list = explode("\n", $rawList);

// Get rid of empty lines
for($i = sizeof($list)-1; $i >= 0; $i--) {
    if($list[$i] == "")
        unset($list[$i]);
}

echo json_encode(array_values($list));

Fix always returning invalid parameter

Fix always returning invalid parameter


<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 21/04/2014
 * Time: 23:01
 */

namespace PhpDorset\Presentation;

/**
 * Class TalkRepository
 * @package PhpDorset\Presentation
 */
class PresentationRepository
{
    /**
     * @var array
     */
    protected $cues;

    /**
     * @param string $cueDatabase
     */
    public function __construct($cueDatabase)
    {
        $this->cues = json_decode(file_get_contents($cueDatabase), true);
    }

    /**
     * @param string $year
     * @param string $month
     * @return array
     */
    public function fetchCues($year, $month)
    {
        return $this->cues[$year][$month]['cues'];
    }

    /**
     * @return array
     */
    public function fetchAll()
    {
        return $this->cues;
    }
}

<?php
/**
 * Created by PhpStorm.
 * User: alex
 * Date: 21/04/2014
 * Time: 23:01
 */

namespace PhpDorset\Presentation;

/**
 * Class PresentationRepository
 * @package PhpDorset\Presentation
 */
class PresentationRepository
{
    /**
     * @var array
     */
    protected $cues;

    /**
     * @param string $cueDatabase
     */
    public function __construct($cueDatabase)
    {
        $this->cues = json_decode(file_get_contents($cueDatabase), true);
    }

    /**
     * @param string $year
     * @param string $month
     * @return array
     */
    public function fetchCues($year, $month)
    {
        return $this->cues[$year][$month]['cues'];
    }

    /**
     * @return array
     */
    public function fetchAll()
    {
        return $this->cues;
    }
}

Update old reference to talk class

Update old reference to talk class

Signed-off-by: Alex Ross <d74d0b805f1f1a75a685a24ac9c38635e4306e23@gmail.com>


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

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

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

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

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

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

    return $result;
  }

  public function getPortletCaption() {
    return '';
  }

}

class PageWithImage_Controller extends Page_Controller {

}

FIX: Remove leading space that caused the pages tab to break


<?php

namespace UghAuthentication\Authentication;

use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\AuthenticationServiceInterface;
use Zend\Authentication\Storage\StorageInterface;

class AuthenticationService implements AuthenticationServiceInterface
{

    /** @var AdapterInterface */
    private $adapter;

    /** @var StorageInterface */
    private $storage;

    public function __construct(StorageInterface $storage, AdapterInterface $adapter)
    {
        $this->adapter = $adapter;
        $this->storage = $storage;
    }

    public function authenticate()
    {
        $result = $this->adapter->authenticate();

        if ($this->hasIdentity()) {
            $this->clearIdentity();
        }

        if ($result->isValid()) {
            $this->storage->write($result->getIdentity());
        }

        return $result;
    }

    public function clearIdentity()
    {
        $this->storage->clear();
    }

    public function getIdentity()
    {
        return $this->storage->read();
    }

    public function hasIdentity()
    {
        return !$this->storage->isEmpty();
    }
}

<?php

namespace UghAuthentication\Authentication;

use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\AuthenticationServiceInterface;
use Zend\Authentication\Result;
use Zend\Authentication\Storage\StorageInterface;

class AuthenticationService implements AuthenticationServiceInterface
{

    /** @var AdapterInterface */
    private $adapter;

    /** @var StorageInterface */
    private $storage;

    /**
     *
     * @param StorageInterface $storage
     * @param AdapterInterface $adapter
     */
    public function __construct(StorageInterface $storage, AdapterInterface $adapter)
    {
        $this->adapter = $adapter;
        $this->storage = $storage;
    }

    /**
     *
     * @return Result
     */
    public function authenticate()
    {
        $result = $this->adapter->authenticate();

        if ($this->hasIdentity()) {
            $this->clearIdentity();
        }

        if ($result->isValid()) {
            $this->storage->write($result->getIdentity());
        }

        return $result;
    }

    public function clearIdentity()
    {
        $this->storage->clear();
    }

    public function getIdentity()
    {
        return $this->storage->read();
    }

    /**
     *
     * @return boolean
     */
    public function hasIdentity()
    {
        return !$this->storage->isEmpty();
    }
}

Add type hints to functions

Add type hints to functions


<?php

namespace Construct;

class GitAttributes
{
    /**
     * The files to ignore on exporting.
     *
     * @var array
     */
    private $exportIgnores = [];

    /**
     * The directories and files to ignore in Git repositories.
     *
     * @var array
     */
    private $gitIgnores = ['/vendor', 'composer.lock'];

    /**
     * Get the export ignores
     *
     * @return array
     */
    public function getExportIgnores()
    {
        return $this->exportIgnores;
    }

    /**
     * Add a file to the export ignores
     *
     * @param string $ignore
     *
     * @return  void
     */
    public function addExportIgnore($ignore)
    {
        $this->exportIgnores[] = $ignore;
    }

    /**
     * Get the directories and files to ignore on git repositories.
     *
     * @return array
     */
    public function getGitIgnores()
    {
        return $this->gitIgnores;
    }

    /**
     * Add a file to the .gitignore
     *
     * @param string $ignore
     *
     * @return  void
     */
    public function addGitIgnore($ignore)
    {
        $this->gitIgnores[] = $ignore;
    }
}

<?php

namespace Construct;

class GitAttributes
{
    /**
     * The files to ignore on exporting.
     *
     * @var array
     */
    private $exportIgnores = [];

    /**
     * The directories and files to ignore in Git repositories.
     *
     * @var array
     */
    private $gitIgnores = ['/vendor', 'composer.lock'];

    /**
     * Get the export ignores
     *
     * @return array
     */
    public function getExportIgnores()
    {
        return $this->exportIgnores;
    }

    /**
     * Add a file to the export ignores
     *
     * @param string $ignore
     *
     * @return  void
     */
    public function addExportIgnore($ignore)
    {
        $this->exportIgnores[] = $ignore;
    }

    /**
     * Remove a file from the export ignores
     *
     * @param string $ignore
     *
     * @return  void
     */
    public function removeExportIgnore($ignore)
    {
        unset($this->exportIgnores[$ignore]);
    }

    /**
     * Get the directories and files to ignore on git repositories.
     *
     * @return array
     */
    public function getGitIgnores()
    {
        return $this->gitIgnores;
    }

    /**
     * Add a file to the .gitignore
     *
     * @param string $ignore
     *
     * @return  void
     */
    public function addGitIgnore($ignore)
    {
        $this->gitIgnores[] = $ignore;
    }
}

Add method to remove an export git ignore.


<?php
declare(strict_types=1);

namespace block\dbblock;

use app;
use arr;
use attr;

function render(array $block): string
{
    $data = $block['cfg']['data'];

    if (!$data || !($attrs = arr\extract($data['_entity']['attr'], $block['cfg']['attr_id']))) {
        return '';
    }

    $html = '';

    foreach ($attrs as $attr) {
        $cfg = ['wrap' => true] + (in_array($attr['id'], ['file_id', 'title']) ? ['link' => $data['link']] : []);
        $html .= attr\viewer($data, $attr, $cfg);
    }

    if ($html) {
        return app\html('section', ['class' => str_replace('_', '-', $block['cfg']['data']['entity_id'])], $html);
    }

    return '';
}

<?php
declare(strict_types=1);

namespace block\dbblock;

use app;
use arr;
use attr;

function render(array $block): string
{
    $data = $block['cfg']['data'];

    if (!$data || !($attrs = arr\extract($data['_entity']['attr'], $block['cfg']['attr_id']))) {
        return '';
    }

    $html = '';

    foreach ($attrs as $attr) {
        $cfg = ['wrap' => true] + (in_array($attr['id'], ['file_id', 'title']) ? ['link' => $data['link']] : []);
        $html .= attr\viewer($data, $attr, $cfg);
    }

    if ($html) {
        return app\html('section', ['data-entity' => $block['cfg']['data']['entity_id']], $html);
    }

    return '';
}

Remove some hidden magic + adjust output to be compatible with view block


<?php
return [
    'module_layouts' => [
        'Application' => 'layout/admin',
        'User' => 'layout/admin',
        'Admin' => 'layout/admin',
        'Landing' => 'layout/3columns',
        'Landing/Index' => 'layout/layout',
        //'Landing/ContactUs' => 'layout/layout',
        //'Blog' => 'layout/layout',
        //'Mission' => 'layout/layout',
        'Mission/Blog' => 'layout/mission',
    ],
];

<?php
return [
    'module_layouts' => [
        'Application' => 'layout/admin',
        'User' => 'layout/admin',
        'Admin' => 'layout/admin',
        'Landing' => 'layout/3columns',
        'Landing/Index' => 'layout/layout',
        //'Landing/ContactUs' => 'layout/layout',
        'Blog' => 'layout/3columns',
        //'Mission' => 'layout/layout',
        'Mission/Blog' => 'layout/mission',
    ],
];

Change news layout to 3columns

Change news layout to 3columns


<?php
/**
 * The sidebar containing the main widget area
 * Implement your custom sidebar to this file.
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package air
 */

?>

<aside id="secondary" class="widget-area">
</aside><!-- #secondary -->

<?php
/**
 * The sidebar containing the main widget area
 * Implement your custom sidebar to this file.
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package air
 */
if ( ! is_active_sidebar( 'sidebar-1' ) ) {
  return;
}
?>

<aside id="secondary" class="widget-area">
  <?php dynamic_sidebar( 'sidebar-1' ); ?>
</aside><!-- #secondary -->

Add default widget area as recommended in best practices


<?php

namespace KnpU\OAuth2ClientBundle\DependencyInjection\Providers;

use KnpU\OAuth2ClientBundle\Client\Provider\InstagramClient;
use League\OAuth2\Client\Provider\Instagram;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;

class InstagramProviderConfigurator implements ProviderConfiguratorInterface
{
    public function buildConfiguration(NodeBuilder $node)
    {
        // no options...
    }

    public function getProviderClass(array $config)
    {
        return Instagram::class;
    }

    public function getProviderOptions(array $config)
    {
        return array(
            'clientId' => $config['clientId'],
            'clientSecret' => $config['clientSecret'],
        );
    }

    public function getPackagistName()
    {
        return 'league/oauth2-instagram';
    }

    public function getLibraryHomepage()
    {
        return 'https://github.com/thephpleague/oauth2-instagram';
    }

    public function getProviderDisplayName()
    {
        return 'Instagram';
    }

    public function getClientClass(array $config)
    {
        return InstagramClient::class;
    }
}

<?php

namespace KnpU\OAuth2ClientBundle\DependencyInjection\Providers;

use KnpU\OAuth2ClientBundle\Client\Provider\InstagramClient;
use League\OAuth2\Client\Provider\Instagram;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;

class InstagramProviderConfigurator implements ProviderConfiguratorInterface
{
    public function buildConfiguration(NodeBuilder $node)
    {
        // no options...
    }

    public function getProviderClass(array $config)
    {
        return Instagram::class;
    }

    public function getProviderOptions(array $config)
    {
        return array(
            'clientId' => $config['client_id'],
            'clientSecret' => $config['client_secret'],
        );
    }

    public function getPackagistName()
    {
        return 'league/oauth2-instagram';
    }

    public function getLibraryHomepage()
    {
        return 'https://github.com/thephpleague/oauth2-instagram';
    }

    public function getProviderDisplayName()
    {
        return 'Instagram';
    }

    public function getClientClass(array $config)
    {
        return InstagramClient::class;
    }
}

Fix name of config keys

Fix name of config keys


<?php

namespace Oro\Bundle\SegmentBundle\Form\Type;

use Doctrine\Common\Persistence\ManagerRegistry;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SegmentChoiceType extends AbstractType
{
    /** @var ManagerRegistry */
    protected $registry;

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

    /**
     * SegmentNameChoiceType constructor.
     * @param ManagerRegistry $registry
     * @param string          $entityClass
     */
    public function __construct(ManagerRegistry $registry, $entityClass)
    {
        $this->registry = $registry;
        $this->entityClass = $entityClass;
    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('placeholder', 'oro.segment.form.segment_choice.placeholder');
        $resolver->setRequired('entityClass');
        $resolver->setNormalizer(
            'choices',
            function (OptionsResolver $options) {
                $repo = $this->registry->getManagerForClass($this->entityClass)->getRepository($this->entityClass);

                return $repo->findByEntity($options['entityClass']);
            }
        );
        $resolver->setAllowedTypes('entityClass', ['null', 'string']);
    }

    /**
     * {@inheritDoc}
     */
    public function getParent()
    {
        return ChoiceType::class;
    }
}

<?php

namespace Oro\Bundle\SegmentBundle\Form\Type;

use Doctrine\Common\Persistence\ManagerRegistry;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SegmentChoiceType extends AbstractType
{
    /** @var ManagerRegistry */
    protected $registry;

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

    /**
     * @param ManagerRegistry $registry
     * @param string          $entityClass
     */
    public function __construct(ManagerRegistry $registry, $entityClass)
    {
        $this->registry = $registry;
        $this->entityClass = $entityClass;
    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('placeholder', 'oro.segment.form.segment_choice.placeholder');
        $resolver->setRequired('entityClass');
        $resolver->setNormalizer(
            'choices',
            function (OptionsResolver $options) {
                $repo = $this->registry->getManagerForClass($this->entityClass)->getRepository($this->entityClass);

                return $repo->findByEntity($options['entityClass']);
            }
        );
        $resolver->setAllowedTypes('entityClass', ['null', 'string']);
    }

    /**
     * {@inheritDoc}
     */
    public function getParent()
    {
        return ChoiceType::class;
    }
}

BB-7975: Add to configuration select with segment lists
- cs fix


<?php
chdir(__DIR__);
if (file_exists(__DIR__ . '/../vendor/autoload.php')){
    require_once __DIR__ . '/../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
    require_once __DIR__ . '/../../../vendor/autoload.php';
} else{
    throw new RuntimeException('vendor/autoload.php could not be found. Did you run `php composer.phar install`?');
}

$autoloader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
$autoloader->registerNamespace('HttpVerbExtraction', __DIR__ . '/../src/HttpVerbExtraction');
$autoloader->register();

<?php
chdir(__DIR__);
if (file_exists(__DIR__ . '/../vendor/autoload.php')){
    require_once __DIR__ . '/../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../vendor/autoload.php')) {
    require_once __DIR__ . '/../../../vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../../../../vendor/autoload.php')) {
    require_once __DIR__ . '/../../../../vendor/autoload.php';
} else{
    throw new RuntimeException('vendor/autoload.php could not be found. Did you run `php composer.phar install`?');
}

$autoloader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
$autoloader->registerNamespace('HttpVerbExtraction', __DIR__ . '/../src/HttpVerbExtraction');
$autoloader->register();

Add a condition to check a directory deeper for autoload file


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

use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class ProducerRepository
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProducerRepository extends AbstractEntityRepository implements ProducerRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDataSetQueryBuilder()
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->groupBy('producer.id');
        $queryBuilder->leftJoin('producer.translations', 'producer_translation');
        $queryBuilder->leftJoin('producer.products', 'producer_products');
        $queryBuilder->leftJoin('producer.shops', 'producer_shops');

        return $queryBuilder;
    }
}

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

use Doctrine\ORM\QueryBuilder;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;

/**
 * Class ProducerRepository
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class ProducerRepository extends AbstractEntityRepository implements ProducerRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDataSetQueryBuilder() : QueryBuilder
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->groupBy('producer.id');
        $queryBuilder->leftJoin('producer.translations', 'producer_translation');
        $queryBuilder->leftJoin('producer.products', 'producer_products');
        $queryBuilder->leftJoin('producer.shops', 'producer_shops');

        return $queryBuilder;
    }
}

Return types in repositories & dataset

Return types in repositories & dataset


<?php

namespace Oro\Bundle\NavigationBundle\Provider;

use Oro\Bundle\NavigationBundle\Entity\AbstractMenuUpdate;

interface MenuUpdateProviderInterface
{
    /**
     * Retrieve list of menu updates
     *
     * @return AbstractMenuUpdate[]
     */
    public function getUpdates();
}

<?php

namespace Oro\Bundle\NavigationBundle\Provider;

use Oro\Bundle\NavigationBundle\Entity\AbstractMenuUpdate;

interface MenuUpdateProviderInterface
{
    /**
     * Retrieve list of menu updates
     *
     * @param string $menu
     *
     * @return AbstractMenuUpdate[]
     */
    public function getUpdates($menu);
}

BB-4399: Create MenuUpdateBuilder with methods
- added $menu argument to MenuUpateProviderInterface


<?php
namespace wcf\system\template;
use wcf\system\WCF;

/**
 * Loads and displays templates in emails.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Template
 */
class EmailTemplateEngine extends TemplateEngine {
	/**
	 * @inheritDoc
	 */
	protected $environment = 'email';

	/**
	 * @inheritDoc
	 */
	public function getTemplateGroupID() {
		static $initialized = false;

		if (!$initialized) {
			$sql = "SELECT	templateGroupID
				FROM	wcf".WCF_N."_template_group
				WHERE	templateGroupFolderName = ?";
			$statement = WCF::getDB()->prepareStatement($sql);
			$statement->execute(['_wcf_email/']);

			parent::setTemplateGroupID($statement->fetchSingleColumn());
		}

		return parent::getTemplateGroupID();
	}

	/**
	 * This method always throws, because changing the template group is not supported.
	 *
	 * @param	integer		$templateGroupID
	 * @throws	\BadMethodCallException
	 */
	public function setTemplateGroupID($templateGroupID) {
		throw new \BadMethodCallException("You may not change the template group of the email template engine");
	}
}

<?php
namespace wcf\system\template;
use wcf\system\WCF;

/**
 * Loads and displays templates in emails.
 *
 * @author	Tim Duesterhus
 * @copyright	2001-2016 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	WoltLabSuite\Core\System\Template
 */
class EmailTemplateEngine extends TemplateEngine {
	/**
	 * @inheritDoc
	 */
	protected $environment = 'email';

	/**
	 * @inheritDoc
	 */
	public function getTemplateGroupID() {
		static $initialized = false;

		if (!$initialized) {
			$sql = "SELECT	templateGroupID
				FROM	wcf".WCF_N."_template_group
				WHERE	templateGroupFolderName = ?";
			$statement = WCF::getDB()->prepareStatement($sql);
			$statement->execute(['_wcf_email/']);

			parent::setTemplateGroupID($statement->fetchSingleColumn());
			$initialized = true;
		}

		return parent::getTemplateGroupID();
	}

	/**
	 * This method always throws, because changing the template group is not supported.
	 *
	 * @param	integer		$templateGroupID
	 * @throws	\BadMethodCallException
	 */
	public function setTemplateGroupID($templateGroupID) {
		throw new \BadMethodCallException("You may not change the template group of the email template engine");
	}
}

Set $initialized flag after initialization in EmailTemplateEngine


<?php

/**
 * Utility class that works with deleting files and directories.
 */
class DeleteUtils {

   /**
    * Delete all files and directories within the root directory.
    *
    * @param   String   The absolute path to the root directory.
    */
   public static function rm_dir($path) {
      foreach(self::serialize_dir($path) as $item) {
         $absolute_path = $path . DIRECTORY_SEPARATOR . $item;

         if(is_dir($absolute_path) && !self::is_empty($absolute_path)) {
            self::rm_dir($absolute_path);
            rmdir($absolute_path);
         } else if(is_dir($absolute_path)) {
            rmdir($absolute_path);
         } else {
            unlink($absolute_path);
         }
      }
   }

   /**
    * Checks to see if a directory is empty
    *
    * @param   String   The absolute path to a directory.
    *
    * @return true or false if the directory is empty or not
    */
   public static function is_empty($dir) {
      return count(self::serialize_dir($dir)) === 0;
   }

   /**
    * Removes . and .. from the array returned from scandir.
    *
    * @param  String  The absolute path to a directory.
    *
    * @return an array from scandir without . and ..
    */
   public static function serialize_dir($dir) {
      return array_diff(scandir($dir), array('.', '..'));
   }
}
?>

<?php

/**
 * Utility class that works with deleting files and directories.
 */
class DeleteUtils {

   /**
    * Delete all files and directories within the root directory.
    *
    * @param   String   The absolute path to the root directory.
    */
   public static function rm_dir($path) {
      foreach(self::serialize_dir($path) as $item) {
         $absolute_path = $path . DIRECTORY_SEPARATOR . $item;

         if(is_dir($absolute_path) && !self::is_empty($absolute_path)) {
            self::rm_dir($absolute_path);
            rmdir($absolute_path);
         } else if(is_dir($absolute_path)) {
            rmdir($absolute_path);
         } else {
            unlink($absolute_path);
         }
      }
   }

   /**
    * Checks to see if a directory is empty
    *
    * @param   String   The absolute path to a directory.
    *
    * @return true or false if the directory is empty or not
    */
   public static function is_empty($dir) {
      return count(self::serialize_dir($dir)) === 0;
   }

   /**
    * Removes . and .. from the array returned from scandir.
    *
    * @param  String  The absolute path to a directory.
    *
    * @return an array from scandir without . and ..
    *
    * @exception throws a runtime exception when scandir returns false
    */
   public static function serialize_dir($dir) {
      if(scandir($dir) === false) {
         throw new \RuntimeException("Scandir returned false, either $dir was not a directory or an I/O error occurred.");
      }

      return array_diff(scandir($dir), array('.', '..'));
   }
}

DeleteUtils::rm_dir('C:\\temp');
?>

Throw RuntimeException is scandir returns false.


<?php

namespace Tests\Result;

use Stratedge\Wye\Result;
use Stratedge\Wye\Wye;

class SetNumRowsTest extends \Tests\TestCase
{
    public function testReturnsSelf()
    {
        $result = Wye::makeResult();

        $this->assertSame($result, $result->setNumRows(123));
    }

    public function testSetsPropertyValue()
    {
        $result = new class (new Wye) extends Result {
            public $num_rows;
        };

        $result->setNumRows(56342);

        $this->assertSame(56342, $result->num_rows);
    }

    public function testSetsPropertyValueAsInteger()
    {
        $result = new class (new Wye) extends Result {
            public $num_rows;
        };

        $result->setNumRows('hello');

        $this->assertSame(0, $result->num_rows);
    }
}

<?php

namespace Tests\Result;

use Stratedge\Wye\Result;
use Stratedge\Wye\Wye;

class SetNumRowsTest extends \Tests\TestCase
{
    public function testReturnsSelf()
    {
        $result = Wye::makeResult();

        $this->assertSame($result, $result->setNumRows(123));
    }

    public function testSetsPropertyValue()
    {
        $result = new Mock(new Wye);

        $result->setNumRows(56342);

        $this->assertSame(56342, $result->num_rows);
    }

    public function testSetsPropertyValueAsInteger()
    {
        $result = new Mock(new Wye);

        $result->setNumRows('hello');

        $this->assertSame(0, $result->num_rows);
    }
}

class Mock extends Result
{
    public $num_rows;
}

Fix unit test that uses PHP7+ functionality


<?php
namespace Craft;

use Cake\Utility\Hash as Hash;

class DateFeedMeFieldType extends BaseFeedMeFieldType
{
    // Templates
    // =========================================================================

    // Public Methods
    // =========================================================================

    public function prepFieldData($element, $field, $fieldData, $handle, $options)
    {
        $data = Hash::get($fieldData, 'data');

        return DateTimeHelper::formatTimeForDb(DateTimeHelper::fromString($data, craft()->timezone));
    }

}

<?php
namespace Craft;

use Cake\Utility\Hash as Hash;

class DateFeedMeFieldType extends BaseFeedMeFieldType
{
    // Templates
    // =========================================================================

    // Public Methods
    // =========================================================================

    public function prepFieldData($element, $field, $fieldData, $handle, $options)
    {
        $data = Hash::get($fieldData, 'data');

        if ($data) {
            return DateTimeHelper::formatTimeForDb(DateTimeHelper::fromString($data, craft()->timezone));
        } else {
            return "";
        }
    }

}

Allow empty date/time to be set of date fields


<?php

namespace Keosu\Gadget\PushNotificationBundle\EventListener;

use Keosu\CoreBundle\KeosuEvents;
use Keosu\CoreBundle\Event\PackageSaveAppEvent;

use Keosu\Gadget\PushNotificationBundle\KeosuGadgetPushNotificationBundle;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Listener responsible to gadget action
 */
class AppConfListener implements EventSubscriberInterface
{

	private $container;

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

	/**
	 * {@inheritDoc}
	 */
	public static function getSubscribedEvents()
	{
		return array(
			KeosuEvents::PACKAGE_GLOBAL_CONFIG_SAV_FORM.KeosuGadgetPushNotificationBundle::PACKAGE_NAME => 'onAppSave',
		);
	}

	public function onAppSave(PackageSaveAppEvent $event)
	{
		$app = $event->getApp();
		$form = $event->getForm();
		$appData = $this->container->get('keosu_core.packagemanager')->getAppDataFolder($app->getId());
		$form['configPackages']['keosu-push']['iosPem']->getData()->move($appData,'ios.pem');
		$configPackage = $app->getConfigPackages();
		$configPackage[KeosuGadgetPushNotificationBundle::PACKAGE_NAME]['iosPem'] = $appData.'ios.pem';
		$app->setConfigPackages($configPackage);
	}
}

<?php

namespace Keosu\Gadget\PushNotificationBundle\EventListener;

use Keosu\CoreBundle\KeosuEvents;
use Keosu\CoreBundle\Event\PackageSaveAppEvent;

use Keosu\Gadget\PushNotificationBundle\KeosuGadgetPushNotificationBundle;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Listener responsible to gadget action
 */
class AppConfListener implements EventSubscriberInterface
{

	private $container;

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

	/**
	 * {@inheritDoc}
	 */
	public static function getSubscribedEvents()
	{
		return array(
			KeosuEvents::PACKAGE_GLOBAL_CONFIG_SAV_FORM.KeosuGadgetPushNotificationBundle::PACKAGE_NAME => 'onAppSave',
		);
	}

	public function onAppSave(PackageSaveAppEvent $event)
	{
		$app = $event->getApp();
		$form = $event->getForm();
		$appData = $this->container->get('keosu_core.packagemanager')->getAppDataFolder($app->getId());
		$iosPem = $form['configPackages']['keosu-push']['iosPem']->getData();
		if($iosPem !== null) {
			$iosPem->move($appData,'ios.pem');
			$configPackage = $app->getConfigPackages();
			$configPackage[KeosuGadgetPushNotificationBundle::PACKAGE_NAME]['iosPem'] = $appData.'ios.pem';
			$app->setConfigPackages($configPackage);
		}
	}
}

Add don't move the file if he'snt uploaded


<?php

declare(strict_types=1);

/*
 * This file is part of SolidInvoice project.
 *
 * (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace SolidInvoice\CoreBundle\Tests;

use AppKernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;

require_once __DIR__.'/../../../app/AppKernel.php';

abstract class KernelAwareTest extends TestCase
{
    use MockeryPHPUnitIntegration;

    /**
     * @var AppKernel
     */
    protected $kernel;

    /**
     * @var EntityManager
     */
    protected $entityManager;

    /**
     * @var Container
     */
    protected $container;

    public function setUp(): void
    {
        $this->kernel = new AppKernel('test', true);
        $this->kernel->boot();

        $this->container = $this->kernel->getContainer();

        parent::setUp();
    }

    public function tearDown(): void
    {
        $this->kernel->shutdown();

        parent::tearDown();
    }
}

<?php

declare(strict_types=1);

/*
 * This file is part of SolidInvoice project.
 *
 * (c) 2013-2017 Pierre du Plessis <info@customscripts.co.za>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace SolidInvoice\CoreBundle\Tests;

use SolidInvoice\Kernel;
use Doctrine\ORM\EntityManager;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;

abstract class KernelAwareTest extends TestCase
{
    use MockeryPHPUnitIntegration;

    /**
     * @var Kernel
     */
    protected $kernel;

    /**
     * @var EntityManager
     */
    protected $entityManager;

    /**
     * @var Container
     */
    protected $container;

    public function setUp(): void
    {
        $this->kernel = new Kernel('test', true);
        $this->kernel->boot();

        $this->container = $this->kernel->getContainer();

        parent::setUp();
    }

    public function tearDown(): void
    {
        $this->kernel->shutdown();

        parent::tearDown();
    }
}

Fix KernalAwareTest to use the correct kernel


<?php

namespace Oro\Bundle\DataGridBundle\Datasource\Orm;

use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;

use Oro\Bundle\DataGridBundle\Datasource\ResultRecord;
use Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator;

/**
 * Iterates query result with elements of ResultRecord type
 */
class IterableResult extends BufferedQueryResultIterator implements IterableResultInterface
{
    /**
     * @var QueryBuilder|Query
     */
    private $source;

    /**
     * Current ResultRecord, populated from query result row
     *
     * @var mixed
     */
    private $current = null;

    /**
     * Constructor
     *
     * @param QueryBuilder|Query $source
     */
    public function __construct($source)
    {
        parent::__construct($source);
        $this->source = $source;
    }

    /**
     * {@inheritDoc}
     */
    public function current()
    {
        return $this->current;
    }

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

        $current = parent::current();
        $this->current = $current === null
            ? null
            : new ResultRecord($current);
    }

    /**
     * {@inheritDoc}
     */
    public function getSource()
    {
        return $this->source;
    }
}

<?php

namespace Oro\Bundle\DataGridBundle\Datasource\Orm;

use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;

use Oro\Bundle\DataGridBundle\Datasource\ResultRecord;
use Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator;

/**
 * Iterates query result with elements of ResultRecord type
 */
class IterableResult extends BufferedQueryResultIterator implements IterableResultInterface
{
    /**
     * @var QueryBuilder|Query
     */
    private $source;

    /**
     * Current ResultRecord, populated from query result row
     *
     * @var mixed
     */
    private $current = null;

    /**
     * Constructor
     *
     * @param QueryBuilder|Query $source
     * @param null|bool $useCountWalker
     */
    public function __construct($source, $useCountWalker = null)
    {
        parent::__construct($source, $useCountWalker);
        $this->source = $source;
    }

    /**
     * {@inheritDoc}
     */
    public function current()
    {
        return $this->current;
    }

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

        $current = parent::current();
        $this->current = $current === null
            ? null
            : new ResultRecord($current);
    }

    /**
     * {@inheritDoc}
     */
    public function getSource()
    {
        return $this->source;
    }
}

Set whether to use count walker for iterator count

Can get the following error:

```
Cannot count query that uses a HAVING clause. Use the output walkers for pagination
```

This can happen when attempting to iterate over a query containing a 'HAVING' clause. Allowing the user to set that a count walker shouldn't be used to get a count, the error won't happen.

Seen when performing a bulk action on a datagrid with a filter enabled that has the `filter_by_having` property set to `true`.


<?php

namespace Modularity\Module\Text;

class Text extends \Modularity\Module
{
    public $slug = 'text';
    public $supports = array('editor');

    public function init()
    {
        $this->nameSingular = __('Text', 'modularity');
        $this->namePlural = __('Texts', 'modularity');
        $this->description = __('Outputs text', 'modularity');
    }

    public function data() : array
    {
        $data = get_fields($this->ID);
        $data['classes'] = implode(' ', apply_filters('Modularity/Module/Classes', array('box', 'box-panel'), $this->post_type, $this->args));
        return $data;
    }

    public function template()
    {
        if (!$this->data['hide_box_frame']) {
            return 'box.blade.php';
        }

        return 'article.blade.php';
    }

    /**
     * Available "magic" methods for modules:
     * init()            What to do on initialization
     * data()            Use to send data to view (return array)
     * style()           Enqueue style only when module is used on page
     * script            Enqueue script only when module is used on page
     * adminEnqueue()    Enqueue scripts for the module edit/add page in admin
     * template()        Return the view template (blade) the module should use when displayed
     */
}

<?php

namespace Modularity\Module\Text;

class Text extends \Modularity\Module
{
    public $slug = 'text';
    public $supports = array('editor');

    public function init()
    {
        $this->nameSingular = __('Text', 'modularity');
        $this->namePlural = __('Texts', 'modularity');
        $this->description = __('Outputs text', 'modularity');
    }

    public function data() : array
    {
        $data = get_fields($this->ID);
        $data['classes'] = implode(' ', apply_filters('Modularity/Module/Classes', array('box', 'box-panel'), $this->post_type, $this->args));
        return $data;
    }

    public function template()
    {
        if (isset($this->data['hide_box_frame']) && !$this->data['hide_box_frame']) {
            return 'box.blade.php';
        }
        return 'article.blade.php';
    }

    /**
     * Available "magic" methods for modules:
     * init()            What to do on initialization
     * data()            Use to send data to view (return array)
     * style()           Enqueue style only when module is used on page
     * script            Enqueue script only when module is used on page
     * adminEnqueue()    Enqueue scripts for the module edit/add page in admin
     * template()        Return the view template (blade) the module should use when displayed
     */
}

Check before use array item.

Check before use array item.


<?php
/**
 * Humbug
 *
 * @category   Humbug
 * @package    Humbug
 * @copyright  Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com)
 * @license    https://github.com/padraic/humbug/blob/master/LICENSE New BSD License
 */

namespace Humbug\Phpunit\Listener;

class TimeCollectorListener implements \PHPUnit_Framework_BaseTestListener
{

    protected $currentSuiteName;

    protected $currentSuiteTime = 0;

    public function __construct(JsonLogger $logger)
    {
        $this->logger = $logger;
    }

    public function startTestSuite(TestSuite $suite)
    {
        $this->currentSuiteName = $suite->getName();
    }

    public function endTest(\PHPUnit_Framework_Test $test, $time)
    {
        $this->currentSuiteTime += $time;
        $this->logger->logTest(
            $this->currentSuiteName,
            $test->getName(),
            $time
        );
    }

    public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        $this->logger->logTestSuite(
            $suite->getName(),
            $this->currentSuiteTime
        );
    }
}

<?php
/**
 * Humbug
 *
 * @category   Humbug
 * @package    Humbug
 * @copyright  Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com)
 * @license    https://github.com/padraic/humbug/blob/master/LICENSE New BSD License
 */

namespace Humbug\Phpunit\Listener;

class TimeCollectorListener extends \PHPUnit_Framework_BaseTestListener
{

    protected $currentSuiteName;

    protected $currentSuiteTime = 0;

    public function __construct(JsonLogger $logger)
    {
        $this->logger = $logger;
    }

    public function startTestSuite(TestSuite $suite)
    {
        $this->currentSuiteName = $suite->getName();
    }

    public function endTest(\PHPUnit_Framework_Test $test, $time)
    {
        $this->currentSuiteTime += $time;
        $this->logger->logTest(
            $this->currentSuiteName,
            $test->getName(),
            $time
        );
    }

    public function endTestSuite(\PHPUnit_Framework_TestSuite $suite)
    {
        $this->logger->logTestSuite(
            $suite->getName(),
            $this->currentSuiteTime
        );
    }
}

Extend base listener not implement

Extend base listener not implement


<?php

namespace Maghead\TableParser;

use InvalidArgumentException;
use Magsql\Driver\BaseDriver;
use Magsql\Driver\MySQLDriver;
use Magsql\Driver\PgSQLDriver;
use Magsql\Driver\SQLiteDriver;
use Maghead\Runtime\Connection;

class TableParser
{
    public static function create(Connection $c, BaseDriver $d)
    {
        if ($d instanceof MySQLDriver) {
            return new MysqlTableParser($c, $d);
        } else if ($d instanceof PgSQLDriver) {
            return new PgsqlTableParser($c, $d);
        } else if ($d instanceof SQLiteDriver) {
            return new SqliteTableParser($c, $d);
        }
        // This is not going to happen
        throw new InvalidArgumentException("table parser driver does not support {$d->getDriverName()} currently.");
    }
}

<?php

namespace Maghead\TableParser;

use InvalidArgumentException;
use Magsql\Driver\BaseDriver;
use Magsql\Driver\MySQLDriver;
use Magsql\Driver\PgSQLDriver;
use Magsql\Driver\SQLiteDriver;
use Maghead\Runtime\Connection;

class TableParser
{
    public static function create(Connection $c, BaseDriver $d)
    {
        if ($d instanceof MySQLDriver) {
            return new MysqlTableParser($c, $d);
        } else if ($d instanceof PgSQLDriver) {
            return new PgsqlTableParser($c, $d);
        } else if ($d instanceof SQLiteDriver) {
            return new SqliteTableParser($c, $d);
        }
        // This is not going to happen
        throw new InvalidArgumentException("table parser driver does not support {$d::ID} currently.");
    }
}

Remove getDriverName method call from the exception message


<?php
  $html = '
';
  if(count($items) > 0) {
    foreach ($items as $item){
         $html.= '

'.$item['title'].'

Precio:  '.$item['price'].'

                            '.__("View details", "minishop").'

';
    }

    $html.= '

';
    echo $html;
    echo $result;
    miniShop::getActions();
  }else{
    echo '
'
          .__('Still not have products','minishop').
          '
';
  }
?>

Remove row class and show only 2 columns


{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}
@extends('master', [
    'titlePrepend' => $user->username,
    'pageDescription' => trans('users.show.page_description', ['username' => $user->username]),
])

@section('content')
    @if (Auth::user() && Auth::user()->isAdmin() && $user->isRestricted())
        @include('objects._notification_banner', [
            'type' => 'warning',
            'title' => trans('admin.users.restricted_banner.title'),
            'message' => trans('admin.users.restricted_banner.message'),
        ])
    @endif

@endsection

@section ("script")
    @parent

    @foreach ($jsonChunks as $name => $data)

    @endforeach

    @include('layout._extra_js', ['src' => 'js/react/modding-profile.js'])
@endsection

{{--
    Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
    See the LICENCE file in the repository root for full licence text.
--}}
@extends('master', [
    'titlePrepend' => blade_safe(str_replace(' ', ' ', e($user->username))),
    'pageDescription' => page_description($user->username),
])

@section('content')
    @if (Auth::user() && Auth::user()->isAdmin() && $user->isRestricted())
        @include('objects._notification_banner', [
            'type' => 'warning',
            'title' => trans('admin.users.restricted_banner.title'),
            'message' => trans('admin.users.restricted_banner.message'),
        ])
    @endif

@endsection

@section ("script")
    @parent

    @foreach ($jsonChunks as $name => $data)

    @endforeach

    @include('layout._extra_js', ['src' => 'js/react/modding-profile.js'])
@endsection

Fix user modding page title and description


<?php
/**
 * Configuration file for the OpenID provider.
 */

$config = array(

	/* The authentication source that should be used. */
	'auth' => 'default-sp',

	/* The name of the attribute which contains the username of the user. */
	'username_attribute' => 'uid',

	/* The directory where OpenID data is stored. */
	'filestore' => '/tmp/ssp-openid-provider',

);

<?php
/**
 * Configuration file for the OpenID provider.
 */

$config = array(

	/* The authentication source that should be used. */
	'auth' => 'default-sp',

	/* The name of the attribute which contains the username of the user. */
	'username_attribute' => 'uid',

	/* The directory where OpenID data is stored. */
	'filestore' => '/var/lib/simplesamlphp-openid-provider',

);

openidProvider: Change the default directory for the data store.

The default configuration uses a directory in /tmp, which may allow
an user to create this directory before simpleSAMLphp attempts to
create it. This can allow the user to overwrite files the webserver has
access to.

This patch changes the default directory.


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

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

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

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

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

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

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

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

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

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

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

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

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

$np=YleNowplaying::create($a);

$cur=$np->getCurrent();
print_r($cur);

$isv=$np->isValid();
print_r($isv);
?>

Add tests for isvalid and current

Add tests for isvalid and current


<?php

declare(strict_types=1);

namespace Reinfi\DependencyInjection\Annotation;

use Psr\Container\ContainerInterface;

/**
 * @package Reinfi\DependencyInjection\Annotation
 *
 * @Annotation
 * @Target({"PROPERTY", "METHOD"})
 */
final class InjectDoctrineRepository extends AbstractAnnotation
{
    /**
     * @var string
     */
    private $entityManager = 'Doctrine\ORM\EntityManager';

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

    /**
     * @param array $values
     */
    public function __construct(array $values)
    {
        if (!isset($values['value'])) {
            if (isset($values['em'])) {
                $this->entityManager = $values['em'];
            }

            $this->entity = $values['entity'];

            return;
        }

        $this->entity = $values['value'];
    }

    /**
     * @inheritDoc
     */
    public function __invoke(ContainerInterface $container)
    {
        $container = $this->determineContainer($container);

        return $container->get($this->entityManager)->getRepository($this->entity);
    }
}

<?php

declare(strict_types=1);

namespace Reinfi\DependencyInjection\Annotation;

use Psr\Container\ContainerInterface;

/**
 * @package Reinfi\DependencyInjection\Annotation
 *
 * @Annotation
 * @Target({"PROPERTY", "METHOD"})
 */
final class InjectDoctrineRepository extends AbstractAnnotation
{
    /**
     * @var string
     */
    private $entityManager = 'Doctrine\ORM\EntityManager';

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

    /**
     * @param array $values
     */
    public function __construct(array $values)
    {
        if (!isset($values['value'])) {
            if (isset($values['em']) || isset($values['entityManager'])) {
                $this->entityManager = $values['entityManager'] ?? $values['em'];
            }

            $this->entity = $values['entity'];

            return;
        }

        $this->entity = $values['value'];
    }

    /**
     * @inheritDoc
     */
    public function __invoke(ContainerInterface $container)
    {
        $container = $this->determineContainer($container);

        return $container->get($this->entityManager)->getRepository($this->entity);
    }
}

Add 'entityManager' as possible annotation value

Reason for this change is that the IDE parses the private attributes of the annotation and provides those as autocomplete.
So this is simply a convenience change.


<?php

use OCA\Mail\HordeTranslationHandler;

require_once __DIR__ .  '/../vendor/autoload.php';
$l = OC_L10N::get('mail');

// bypass Horde Translation system
Horde_Translation::setHandler('Horde_Imap_Client', new HordeTranslationHandler());
Horde_Translation::setHandler('Horde_Mime', new HordeTranslationHandler());

OCP\App::addNavigationEntry(array(
  'id' => 'mail',
  'order' => 1,
  'href' => OCP\Util::linkToRoute( 'mail.page.index' ),
  'icon' => OCP\Util::imagePath( 'mail', 'mail.svg' ),
  'name' => $l->t('Mail'),
));

//OCP\App::registerPersonal('mail','settings');

<?php

use OCA\Mail\HordeTranslationHandler;

$autoload = __DIR__ .  '/../vendor/autoload.php';
if (!is_readable($autoload)) {
	print 'Cannot read "autoload.php". Did you run composer ?'.
	      "
cd path/to/owncloud/apps/mail\n".
	      "curl -sS https://getcomposer.org/installer | php\n".
	      'php composer.phar install
';
	exit;
}
require_once $autoload;
$l = OC_L10N::get('mail');

// bypass Horde Translation system
Horde_Translation::setHandler('Horde_Imap_Client', new HordeTranslationHandler());
Horde_Translation::setHandler('Horde_Mime', new HordeTranslationHandler());

OCP\App::addNavigationEntry(array(
  'id' => 'mail',
  'order' => 1,
  'href' => OCP\Util::linkToRoute( 'mail.page.index' ),
  'icon' => OCP\Util::imagePath( 'mail', 'mail.svg' ),
  'name' => $l->t('Mail'),
));

//OCP\App::registerPersonal('mail','settings');

Check for autoload.php and tell the user to run composer if it's not found


<?php namespace Pingpong\Menus;

use Illuminate\Support\ServiceProvider;

class MenusServiceProvider 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('pingpong/menus');
		$this->requireMenusFile();
	}

	/**
	 * Require the menus file if that file is exists.
	 *
	 * @return void
	 */
	public function requireMenusFile()
	{
		if(file_exists($file = app_path('menus.php')))
		{
			require $file;
		}
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
        $this->app['menus'] = $this->app->share(function($app)
        {
        	return new Menu($app['view'], $app['config']);
        });
	}

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

}

<?php namespace Pingpong\Menus;

use Illuminate\Support\ServiceProvider;

class MenusServiceProvider 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->requireMenusFile();
    }

    /**
     * Require the menus file if that file is exists.
     *
     * @return void
     */
    public function requireMenusFile()
    {
        if (file_exists($file = app_path('Support/menus.php'))) require $file;
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerComponent();

        $this->registerNamespaces();
    }

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

    /**
     * Register package's namespaces.
     *
     * @return void
     */
    protected function registerNamespaces()
    {
        $this->mergeConfigFrom(__DIR__ . '/src/config/config.php', 'menus');
        $this->loadViewsFrom(__DIR__ . '/src/views', 'menus');

        $this->publishes([
            __DIR__ . '/src/config/config.php' => config_path('menus.php'),
            __DIR__ . '/src/views' => base_path('resources/views/vendor/menus'),
        ]);
    }

    /**
     * Register package's component.
     *
     * @return void
     */
    protected function registerComponent()
    {
        $this->app['menus'] = $this->app->share(function ($app)
        {
            return new Menu($app['view'], $app['config']);
        });
    }

}

Update the way to register package's namespaces using L5's way


<?php
class ModelPaymentOmiseOffsite extends Model {
    public function getMethod($address, $total) {
        $this->load->language('payment/omise_offsite');

        if ($this->config->get('omise_offsite_payment_title') != "")
            $payment_title = $this->config->get('omise_offsite_payment_title');
        else
            $payment_title = $this->language->get('text_title');

        return array(
            'code'       => 'omise_offsite',
            'title'      => $payment_title,
            'terms'      => '',
            'sort_order' => $this->config->get('omise_offsite_sort_order')
        );
    }
}

<?php
class ModelPaymentOmiseOffsite extends Model {
    public function getMethod($address, $total) {
        if ($this->config->get('omise_status') != 1) {
            return false;
        }

        $this->load->language('payment/omise_offsite');

        if ($this->config->get('omise_offsite_payment_title') != "")
            $payment_title = $this->config->get('omise_offsite_payment_title');
        else
            $payment_title = $this->language->get('text_title');

        return array(
            'code'       => 'omise_offsite',
            'title'      => $payment_title,
            'terms'      => '',
            'sort_order' => $this->config->get('omise_offsite_sort_order')
        );
    }
}

Disable Internet Banking method if Omise extension is either disabled or uninstalled.


<?php
namespace App\Entity\Fixture;

use App\Entity;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Persistence\ObjectManager;

class Settings extends AbstractFixture
{
    public function load(ObjectManager $em)
    {
        $settings = [
            Entity\Settings::BASE_URL => getenv('INIT_BASE_URL') ?? 'docker.local',
            Entity\Settings::INSTANCE_NAME => getenv('INIT_INSTANCE_NAME') ?? 'local test',
            Entity\Settings::GEOLITE_LICENSE_KEY => getenv('INIT_GEOLITE_LICENSE_KEY') ?? '',
            Entity\Settings::PREFER_BROWSER_URL => 1,
            Entity\Settings::SETUP_COMPLETE => time(),
            Entity\Settings::USE_RADIO_PROXY => 1,
            Entity\Settings::SEND_ERROR_REPORTS => 0,
            Entity\Settings::CENTRAL_UPDATES => Entity\Settings::UPDATES_NONE,
            Entity\Settings::EXTERNAL_IP => '127.0.0.1',
        ];

        foreach ($settings as $setting_key => $setting_value) {
            $record = new Entity\Settings($setting_key);
            $record->setSettingValue($setting_value);
            $em->persist($record);
        }

        $em->flush();
    }
}

<?php
namespace App\Entity\Fixture;

use App\Entity;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Persistence\ObjectManager;

class Settings extends AbstractFixture
{
    public function load(ObjectManager $em)
    {
        $settings = [
            Entity\Settings::BASE_URL => getenv('INIT_BASE_URL') ?? 'docker.local',
            Entity\Settings::INSTANCE_NAME => getenv('INIT_INSTANCE_NAME') ?? 'local test',
            Entity\Settings::GEOLITE_LICENSE_KEY => getenv('INIT_GEOLITE_LICENSE_KEY') ?? '',
            Entity\Settings::PREFER_BROWSER_URL => 1,
            Entity\Settings::SETUP_COMPLETE => time(),
            Entity\Settings::USE_RADIO_PROXY => 1,
            Entity\Settings::SEND_ERROR_REPORTS => 0,
            Entity\Settings::CENTRAL_UPDATES => Entity\Settings::UPDATES_NONE,
            Entity\Settings::EXTERNAL_IP => '127.0.0.1',
        ];

        $isDemoMode = (!empty(getenv('INIT_DEMO_API_KEY') ?? ''));
        if ($isDemoMode) {
            $settings[Entity\Settings::LISTENER_ANALYTICS] = Entity\Analytics::LEVEL_NO_IP;
            $settings[Entity\Settings::CUSTOM_JS_PUBLIC] = <<<EOF
            $(function() {
              if ($('body').hasClass('login-content')) {
                $('input[name="username"]').val('demo@azuracast.com');
                $('input[name="password"]').val('demo');
              }
            });
            EOF;
        }

        foreach ($settings as $setting_key => $setting_value) {
            $record = new Entity\Settings($setting_key);
            $record->setSettingValue($setting_value);
            $em->persist($record);
        }

        $em->flush();
    }
}

Improve UX on demo instance.

Improve UX on demo instance.


<?php

namespace Speicher210\Estimote;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use JMS\Serializer\SerializerInterface;
use Speicher210\Estimote\Exception\ApiException;
use Speicher210\Estimote\Exception\ApiKeyInvalidException;
use Speicher210\Estimote\Model\Beacon as BeaconModel;

/**
 * Abstract resource.
 */
abstract class AbstractResource
{
    /**
     * The API client.
     *
     * @var Client
     */
    protected $client;

    /**
     * Serializer interface to serialize / deserialize the request / responses.
     *
     * @var SerializerInterface
     */
    protected $serializer;

    /**
     * @param Client $client The API client.
     * @param SerializerInterface $serializer Serializer interface to serialize / deserialize the request / responses.
     */
    public function __construct(Client $client, SerializerInterface $serializer)
    {
        $this->client = $client;
        $this->serializer = $serializer;
    }

    /**
     * Create an ApiException from a client exception.
     *
     * @param ClientException $e The client exception.
     * @return ApiException
     */
    protected function createApiException(ClientException $e)
    {
        $response = $e->getResponse();

        if (in_array($response->getStatusCode(), [401, 403], true)) {
            throw new ApiKeyInvalidException();
        }

        throw new ApiException((string)$response->getBody());
    }
}

<?php

declare(strict_types = 1);

namespace Speicher210\Estimote;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use JMS\Serializer\SerializerInterface;
use Speicher210\Estimote\Exception\ApiException;
use Speicher210\Estimote\Exception\ApiKeyInvalidException;

/**
 * Abstract resource.
 */
abstract class AbstractResource
{
    /**
     * The API client.
     *
     * @var Client
     */
    protected $client;

    /**
     * Serializer interface to serialize / deserialize the request / responses.
     *
     * @var SerializerInterface
     */
    protected $serializer;

    /**
     * @param Client $client The API client.
     * @param SerializerInterface $serializer Serializer interface to serialize / deserialize the request / responses.
     */
    public function __construct(Client $client, SerializerInterface $serializer)
    {
        $this->client = $client;
        $this->serializer = $serializer;
    }

    /**
     * Create an ApiException from a client exception.
     *
     * @param ClientException $e The client exception.
     * @return ApiException
     */
    protected function createApiException(ClientException $e): ApiException
    {
        $response = $e->getResponse();

        if (\in_array($response->getStatusCode(), [401, 403], true)) {
            throw new ApiKeyInvalidException();
        }

        return new ApiException((string)$response->getBody());
    }
}

Return instead of throw the exception

Return instead of throw the exception


<?php

namespace Construct\Constructors;

use League\Container\Container;

class Src extends Constructor implements ConstructorContract
{
    /**
     * Folder to store source files.
     *
     * @var string
     */
    protected $srcPath = 'src';

    /**
     * This constructor creates the project's root folder
     * and the src folder inside of it.
     *
     * @return void
     */
    public function run()
    {
        $this->filesystem->makeDirectory($this->settings->getProjectLower());
        $this->filesystem->makeDirectory($this->settings->getProjectLower() . '/' . $this->srcPath);
    }
}

<?php

namespace Construct\Constructors;

use League\Container\Container;

class Src extends Constructor implements ConstructorContract
{
    /**
     * Folder to store source files.
     *
     * @var string
     */
    private $srcPath = 'src';

    /**
     * This constructor creates the project's root folder
     * and the src folder inside of it.
     *
     * @return void
     */
    public function run()
    {
        $this->filesystem->makeDirectory($this->settings->getProjectLower());
        $this->filesystem->makeDirectory($this->settings->getProjectLower() . '/' . $this->srcPath);
    }
}

Use private on the src property.

Use private on the src property.


<?PHP  //$Id$
// This file defines the current version of the
// Moodle code that is being used.  This can be
// compared against the values stored in the
// database to determine whether upgrades should
// be performed (see lib/db/*.php)

$version = 2002110600;   // The current version is a date (YYYYMMDDXX)

$release = "1.0.6.1";  // User-friendly version number

<?PHP  //$Id$
// This file defines the current version of the
// Moodle code that is being used.  This can be
// compared against the values stored in the
// database to determine whether upgrades should
// be performed (see lib/db/*.php)

$version = 2002110700;   // The current version is a date (YYYYMMDDXX)

$release = "1.0.6.2";  // User-friendly version number

Update for course format changes etc

Update for course format changes etc


<?php

namespace Bitverse\Identicon\SVG;

class Svg extends SvgNode
{
    private $width;

    private $height;

    private $children = [];

    /**
     * @param integer $width
     * @param integer $height
     */
    public function __construct($width, $height)
    {
        $this->width = $width;
        $this->height = $height;
    }

    /**
     * @param SvgNode $node
     *
     * @return Svg
     */
    public function addChild(SvgNode $node = null)
    {
        $this->children[] = $node;
        return $this;
    }

    public function __toString()
    {
        return sprintf(
            '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ' .
                'width="%d" height="%d">%s</svg>',
            $this->width,
            $this->height,
            implode('', array_map(function ($node) {
                return (string) $node;
            }, $this->children))
        );
    }
}

<?php

namespace Bitverse\Identicon\SVG;

class Svg extends SvgNode
{
    private $width;

    private $height;

    private $children = [];

    /**
     * @param integer $width
     * @param integer $height
     */
    public function __construct($width, $height)
    {
        $this->width = $width;
        $this->height = $height;
    }

    /**
     * @param SvgNode $node
     *
     * @return Svg
     */
    public function addChild(SvgNode $node = null)
    {
        $this->children[] = $node;
        return $this;
    }

    public function __toString()
    {
        return sprintf(
            '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ' .
                'width="%d" height="%d" viewBox="0 0 %d %d">%s</svg>',
            $this->width,
            $this->height,
            $this->width,
            $this->height,
            implode('', array_map(function ($node) {
                return (string) $node;
            }, $this->children))
        );
    }
}

Add viewBox attr to top level <svg>

Add viewBox attr to top level <svg>


<?php

/*
 * This file is part of PhuninCake.
 *
 ** (c) 2013 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WyriHaximus\PhuninCake\Event;

use Cake\Event\EventListenerInterface;
use WyriHaximus\PhuninNode\Plugins;

class StockPluginsListener implements EventListenerInterface
{
    /**
     * @return array
     */
    public function implementedEvents() {
        return [
            StartEvent::EVENT => 'start',
        ];
    }

    /**
     * @param StartEvent $event
     */
    public function start(StartEvent $event) {
        $event->getNode()->addPlugin(new Plugins\Plugins());
        $event->getNode()->addPlugin(new Plugins\PluginsCategories());
        $event->getNode()->addPlugin(new Plugins\MemoryUsage());
        $event->getNode()->addPlugin(new Plugins\Uptime());
    }
}

<?php

/*
 * This file is part of PhuninCake.
 *
 ** (c) 2013 Cees-Jan Kiewiet
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace WyriHaximus\PhuninCake\Event;

use Cake\Event\EventListenerInterface;
use WyriHaximus\PhuninNode\Plugins;

class StockPluginsListener implements EventListenerInterface
{
    /**
     * @return array
     */
    public function implementedEvents() {
        return [
            StartEvent::EVENT => 'start',
        ];
    }

    /**
     * @param StartEvent $event
     */
    public function start(StartEvent $event) {
        $event->getNode()->addPlugin(new Plugins\Plugins());
        //$event->getNode()->addPlugin(new Plugins\PluginsCategories());
        $event->getNode()->addPlugin(new Plugins\MemoryUsage());
        $event->getNode()->addPlugin(new Plugins\Uptime());
    }
}

Disable PluginsCategories till it is fixed


<?php
    class ReadMore extends Modules {
        public function __init() {
            $this->addAlias("markup_post_text", "more", 4); # Replace "" before markup modules filter it.
        }

        public function more($text, $post = null) {
            if (!is_string($text) or preg_match("//i", $text, $matches) === 0)
                return $text;

            $route = Route::current();
            $controller = $route->controller;

            if ($route->action == "view" or $route->action == "preview" or
                ($controller instanceof MainController and $controller->feed))
                return preg_replace("//i", "", $text);

            $more = oneof(trim(fallback($matches[1])), __("…more", "read_more"));
            $url = (isset($post) and !$post->no_results) ? $post->url() : "#" ;
            $split = preg_split("//i", $text, -1, PREG_SPLIT_NO_EMPTY);

            return $split[0].''.$more.'';
        }

        public function title_from_excerpt($text) {
            $split = preg_split('/<a class="read_more"/', $text);
            return $split[0];
        }
    }

<?php
    class ReadMore extends Modules {
        public function __init() {
            # Replace comment codes before markup modules filters them.
            $this->setPriority("markup_post_text", 4);
        }

        public function markup_post_text($text, $post = null) {
            if (!is_string($text) or !preg_match("//i", $text, $matches))
                return $text;

            $route = Route::current();
            $controller = $route->controller;

            if ($route->action == "view" or ($controller instanceof MainController and $controller->feed))
                return preg_replace("//i", "", $text);

            $more = oneof(trim(fallback($matches[1])), __("…more", "read_more"));
            $url = (isset($post) and !$post->no_results) ? $post->url() : "#" ;
            $split = preg_split("//i", $text, -1, PREG_SPLIT_NO_EMPTY);

            return $split[0].''.$more.'';
        }

        public function title_from_excerpt($text) {
            $split = preg_split('/<a class="read_more"/', $text);
            return $split[0];
        }
    }

Read More module: refactoring and made regex more forgiving


<?php
/**
 * @file
 * A script containing any set-up steps required for PHPUnit testing.
 */

require __DIR__ . '/../vendor/autoload.php';

putenv((new \Platformsh\Cli\CliConfig())->get('application.env_prefix') . 'DRUSH=' . CLI_ROOT . '/vendor/bin/drush');

<?php
/**
 * @file
 * A script containing any set-up steps required for PHPUnit testing.
 */

require __DIR__ . '/../vendor/autoload.php';

$env_prefix = (new \Platformsh\Cli\CliConfig())->get('application.env_prefix');
if (!getenv($env_prefix)) {
    putenv($env_prefix . 'DRUSH=' . CLI_ROOT . '/vendor/bin/drush');
}

Allow Drush location to be overridden for tests


<?php
/**
 * Model
 *
 * @author: Michal Hojgr <michal.hojgr@gmail.com>
 *
 */

class ModLoader {

	/**
	 * @var Cache
	 */
	private $cache;
	/**
	 * @var ModMapper
	 */
	private $modMapper;

	/**
	 * @param Cache $cache
	 * @param ModMapper $modMapper
	 */
	public function __construct(Cache $cache, ModMapper $modMapper)
	{
		$this->cache = $cache;
		$this->modMapper = $modMapper;
	}

	/**
	 * Loads all versions, caches them and in case that
	 * cache was made recently, it reads from cache
	 *
	 * @param int $count how many versions to show
	 * @param int $start
	 * @return array
	 */
	public function getVersions($count, $start = 0) {

		/**
		 * Load from cache
		 */
		$files = $this->cache->getCachedVersions($this->modMapper);

		/**
		 * Get latest version and the others
		 */
		$latest = $files[0];
		unset($files[0]);

		$others = array_values($files);

		// buffer count so it must not count every loop
		$buffer_count = count($others);

		for($i = 0; $i < $count; $i++) {
			if($i < $start || $i > $start + $count)
				unset($others[$i]);
		}

		return array("latest" => $latest, "others" => $others);
	}
}

<?php
/**
 * Model
 *
 * @author: Michal Hojgr <michal.hojgr@gmail.com>
 *
 */

class ModLoader {

	/**
	 * @var Cache
	 */
	private $cache;
	/**
	 * @var ModMapper
	 */
	private $modMapper;

	/**
	 * @param Cache $cache
	 * @param ModMapper $modMapper
	 */
	public function __construct(Cache $cache, ModMapper $modMapper)
	{
		$this->cache = $cache;
		$this->modMapper = $modMapper;
	}

	/**
	 * Loads all versions, caches them and in case that
	 * cache was made recently, it reads from cache
	 *
	 * @param int $count how many versions to show
	 * @param int $start
	 * @return array
	 */
	public function getVersions($count, $start = 0) {

		/**
		 * Load from cache
		 */
		$files = $this->cache->getCachedVersions($this->modMapper);

		/**
		 * Get latest version and the others
		 */
		$latest = $files[0];
		unset($files[0]);

		$others = array_values($files);

		// buffer count so it must not count every loop
		$buffer_count = count($others);

		for($i = 0; $i < $count; $i++) {
			if($i < $start || $i > $start + $buffer_count)
				unset($others[$i]);
		}

		return array("latest" => $latest, "others" => $others);
	}
}

Fix bug - wrong variable after her rename


<?php

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

namespace Symfony\Component\Yaml\Tests;

use Symfony\Component\Yaml\Yaml;

class YamlTest extends \PHPUnit_Framework_TestCase
{
    public function testParseAndDump()
    {
        $data = array('lorem' => 'ipsum', 'dolor' => 'sit');
        $yml = Yaml::dump($data);
        $parsed = Yaml::parse($yml);
        $this->assertEquals($data, $parsed);
    }

    /**
     * @group legacy
     */
    public function testLegacyParseFromFile()
    {
        $this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED);

        $filename = __DIR__.'/Fixtures/index.yml';
        $contents = file_get_contents($filename);
        $parsedByFilename = Yaml::parse($filename);
        $parsedByContents = Yaml::parse($contents);
        $this->assertEquals($parsedByFilename, $parsedByContents);
    }
}

<?php

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

namespace Symfony\Component\Yaml\Tests;

use Symfony\Component\Yaml\Yaml;

class YamlTest extends \PHPUnit_Framework_TestCase
{
    public function testParseAndDump()
    {
        $data = array('lorem' => 'ipsum', 'dolor' => 'sit');
        $yml = Yaml::dump($data);
        $parsed = Yaml::parse($yml);
        $this->assertEquals($data, $parsed);
    }

    /**
     * @group legacy
     */
    public function testLegacyParseFromFile()
    {
        $filename = __DIR__.'/Fixtures/index.yml';
        $contents = file_get_contents($filename);
        $parsedByFilename = Yaml::parse($filename);
        $parsedByContents = Yaml::parse($contents);
        $this->assertEquals($parsedByFilename, $parsedByContents);
    }
}

[PhpUnitBridge] Enforce @-silencing of deprecation notices according to new policy


<?php
/**
 * The TestHelper.php file is loaded before running a test suite,
 * so it can be used to bootstrap the test suite with common helpers,
 * and configuration.
 */

// Require system under test
require dirname(__FILE__) . '/../lib/Calendar.php';

/**
 * Generic project-specific test case, where helper methods available
 * to all other test cases can be defined.
 */
class CalendarTestCase extends PHPUnit_Framework_TestCase {

}

<?php
/**
 * The TestHelper.php file is loaded before running a test suite,
 * so it can be used to bootstrap the test suite with common helpers,
 * and configuration.
 */

// Require system under test
require dirname(__FILE__) . '/../lib/Calendar.php';

/**
 * Generic project-specific test case, where helper methods available
 * to all other test cases can be defined.
 */
class CalendarTestCase extends \PHPUnit_Framework_TestCase {

}

Make sure to use top-level phpunit class


<?php declare(strict_types=1);

namespace Thepixeldeveloper\Sitemap;

use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;

abstract class Collection implements VisitorInterface
{
    /**
     * @var VisitorInterface[]
     */
    private $items;

    public function add(VisitorInterface $value)
    {
        $type = $this->type();

        if ($value instanceof $type) {
            $this->items[] = $value;
        }

        throw new \InvalidArgumentException('$value needs to be an instance of ' . $type);
    }

    /**
     * @return VisitorInterface[]
     */
    public function all(): array
    {
        return $this->items;
    }

    abstract public function type(): string;
}

<?php declare(strict_types=1);

namespace Thepixeldeveloper\Sitemap;

use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;

abstract class Collection implements VisitorInterface
{
    /**
     * @var VisitorInterface[]
     */
    private $items;

    public function add(VisitorInterface $value)
    {
        $type = $this->type();

        if ($value instanceof $type) {
            $this->items[] = $value;
        } else {
            throw new \InvalidArgumentException('$value needs to be an instance of ' . $type);
        }
    }

    /**
     * @return VisitorInterface[]
     */
    public function all(): array
    {
        return $this->items;
    }

    abstract public function type(): string;
}

Fix bug with the collection validation.

Fix bug with the collection validation.


<?php
namespace Mapbender\QuerySearchBundle;

use Mapbender\CoreBundle\Component\MapbenderBundle;

/**
 * Mapbender search bundle
 *
 * @author Andriy Oblivantsev
 */
class MapbenderSearchBundle extends MapbenderBundle
{
    /**
     * @inheritdoc
     */
    public function getElements()
    {
        return array(
            'Mapbender\SearchBundle\Element\Search'
        );
    }
}

<?php
namespace Mapbender\SearchBundle;

use Mapbender\CoreBundle\Component\MapbenderBundle;

/**
 * Mapbender search bundle
 *
 * @author Andriy Oblivantsev
 */
class MapbenderSearchBundle extends MapbenderBundle
{
    /**
     * @inheritdoc
     */
    public function getElements()
    {
        return array(
            'Mapbender\SearchBundle\Element\Search'
        );
    }
}

Fix search bundle name space

Fix search bundle name space


<?php

namespace AlgoWeb\PODataLaravel\Models;

use AlgoWeb\PODataLaravel\Models\MetadataTrait;
use Illuminate\Database\Eloquent\Model as Model;
use Illuminate\Database\Schema\Builder as SchemaBuilder;

class TestModel extends Model
{
    use MetadataTrait;

    public function getTable()
    {
        return 'testmodel';
    }

    public function getConnectionName()
    {
        return 'testconnection';
    }

    protected function getAllAttributes()
    {
        return ['id' => 0, 'name' => '', 'added_at' => '', 'weight' => '', 'code' => ''];
    }

    public function getFillable()
    {
        return [ 'name', 'added_at', 'weight', 'code'];
    }
}

<?php

namespace AlgoWeb\PODataLaravel\Models;

use AlgoWeb\PODataLaravel\Models\MetadataTrait;
use Illuminate\Database\Eloquent\Model as Model;
use Illuminate\Database\Schema\Builder as SchemaBuilder;

class TestModel extends Model
{
    use MetadataTrait;
    protected $metaArray;

    public function __construct(array $meta = null)
    {
        if (isset($meta)) {
            $this->metaArray = $meta;
        }
        parent::__construct();
    }

    public function getTable()
    {
        return 'testmodel';
    }

    public function getConnectionName()
    {
        return 'testconnection';
    }

    protected function getAllAttributes()
    {
        return ['id' => 0, 'name' => '', 'added_at' => '', 'weight' => '', 'code' => ''];
    }

    public function getFillable()
    {
        return [ 'name', 'added_at', 'weight', 'code'];
    }

    public function metadata()
    {
        if (isset($this->metaArray)) {
            return $this->metaArray;
        }
        return parent::metadata();
    }
}

Make test model metadata configurable

Make test model metadata configurable


<?php
/**
 * Bootstrapping File for phpseclib Test Suite
 *
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
 */

// Set up include path accordingly. This is especially required because some
// class files of phpseclib require() other dependencies.
set_include_path(implode(PATH_SEPARATOR, array(
	dirname(__FILE__) . '/../phpseclib/',
	get_include_path(),
)));

function phpseclib_autoload($class)
{
	$file = str_replace('_', '/', $class) . '.php';

	require $file;
}

spl_autoload_register('phpseclib_autoload');

<?php
/**
 * Bootstrapping File for phpseclib Test Suite
 *
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
 */

// Set up include path accordingly. This is especially required because some
// class files of phpseclib require() other dependencies.
set_include_path(implode(PATH_SEPARATOR, array(
	dirname(__FILE__) . '/../phpseclib/',
	dirname(__FILE__) . '/',
	get_include_path(),
)));

function phpseclib_is_includable($suffix)
{
	foreach (explode(PATH_SEPARATOR, get_include_path()) as $prefix)
	{
		$ds = substr($prefix, -1) == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR;
		$file = $prefix . $ds . $suffix;

		if (file_exists($file))
		{
			return true;
		}
	}

	return false;
}

function phpseclib_autoload($class)
{
	$file = str_replace('_', '/', $class) . '.php';

	if (phpseclib_is_includable($file))
	{
		require $file;
	}
}

spl_autoload_register('phpseclib_autoload');

[task/fix-test-autoloader] Fix autoloader to support failing/erroring tests.

Before showing error output PHPUnit 3.7.x calls class_exists() on some PHPUnit
Extension class names that may not exist. Calling class_exists() already
triggers the autoload function in which require() then obviously fails.

We now check whether a file is includable by simply looping over all possible
include directories.


<?
// Send a reply with information when an incoming SMS is received
//
// 1. Upload the below script to your web server
// 2. Allocate a 46elks number
// 3. Change sms_url on the 46elks number to your script URL
// 4. Send an SMS to your 46elks number with any contents, and get an SMS reply
//
// Hint! To create different commands, check out $_POST['message']

$hours = array(
  'Mon' => '08:00 - 17:00',
  'Tue' => '08:00 - 17:00',
  'Wed' => '08:00 - 19:00',
  'Thu' => '08:00 - 17:00',
  'Fri' => '08:00 - 17:00',
  'Sat' => '10:00 - 16:00'
);

$weekday = date('D');

if (isset($hours[$weekday]))
  echo 'We are open today between '. $hours[$weekday];
else
  echo 'We are closed today';

?>

<?php
// Send a reply with information when an incoming SMS is received
//
// 1. Upload the below script to your web server
// 2. Allocate a 46elks number
// 3. Change sms_url on the 46elks number to your script URL
// 4. Send an SMS to your 46elks number with any contents, and get an SMS reply
//
// Hint! To create different commands, check out $_POST['message']

$hours = array(
  'Mon' => '08:00 - 17:00',
  'Tue' => '08:00 - 17:00',
  'Wed' => '08:00 - 19:00',
  'Thu' => '08:00 - 17:00',
  'Fri' => '08:00 - 17:00',
  'Sat' => '10:00 - 16:00'
);

$weekday = date('D');

if (isset($hours[$weekday]))
  echo 'We are open today between '. $hours[$weekday];
else
  echo 'We are closed today';

?>

Change from short to standard open tag

Change from short to standard open tag

https://wiki.php.net/rfc/deprecate_php_short_tags


<?php

namespace Md\Phunkie\Cats;

/**
 * Lens<A,B>
 */
class Lens
{
    private $g;
    private $s;

    /**
     * @param callable<A, B> $g
     * @param callable<(A,B), A> $s
     */
    public function __construct(callable $g, callable $s)
    {
        $this->g = $g;
        $this->s = $s;
    }

    /**
     * @param A $a
     * @return B
     */
    public function get($a)
    {
        return call_user_func($this->g, $a);
    }

    /**
     * @param B $b
     * @param A $a
     * @return A
     */
    public function set($b, $a)
    {
        return call_user_func_array($this->s, [$b, $a]);
    }

    /**
     * @param callable<B,B> $f
     * @param A $a
     * @return A
     */
    public function mod(callable $f, $a)
    {
        return $this->set($f($this->get($a)), $a);
    }

    public function andThen(Lens $l): Lens
    {
        return new Lens(
            function($a) use ($l) { return $l->get($this->get($a)); },
            function($c, $a) use ($l) { return $this->mod(function($b) use ($l, $c) { return $l->set($c, $b); }, $a); }
        );
    }

    public function compose(Lens $that): Lens
    {
        return $that->andThen($this);
    }
}

<?php

namespace Md\Phunkie\Cats;

class Lens
{
    private $g;
    private $s;

    public function __construct(callable $g, callable $s)
    {
        $this->g = $g;
        $this->s = $s;
    }

    public function get($a)
    {
        return call_user_func($this->g, $a);
    }

    public function set($b, $a)
    {
        return call_user_func_array($this->s, [$b, $a]);
    }

    public function mod(callable $f, $a)
    {
        return $this->set($f($this->get($a)), $a);
    }

    public function andThen(Lens $l): Lens
    {
        return new Lens(
            function($a) use ($l) { return $l->get($this->get($a)); },
            function($c, $a) use ($l) { return $this->mod(function($b) use ($l, $c) { return $l->set($c, $b); }, $a); }
        );
    }

    public function compose(Lens $that): Lens
    {
        return $that->andThen($this);
    }
}

Remove phpdocs from lens as it is messing up with the IDE


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Models;

use Illuminate\Database\Eloquent\Model;

class AbstractModel extends Model
{
    //
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Models;

use Rinvex\Tenants\Traits\Tenantable;
use Illuminate\Database\Eloquent\Model;

class AbstractModel extends Model
{
    use Tenantable;
}

Apply tenantable global scope on Eloquent Presence Verifier (i.e. used in validation rules like unique & exists)


<?php namespace Sauce\Plugins;

abstract class Plugin {

    /**
     * The plugin settings
     *
     * @var array
     */
    protected $settings = [];

    /**
     * Run a plugin
     *
     * @param string $from
     * @param string $to
     * @return mixed
     */
    abstract protected function run($from, $to);

    /**
     * Gets called when the object is called as a function
     *
     * @param array $settings
     * @return mixed
     */
    public function __invoke(array $settings = [])
    {
        $this->settings = $settings;

        return $this;
    }

}

<?php namespace Sauce\Plugins;

abstract class Plugin {

    /**
     * The plugin settings
     *
     * @var array
     */
    protected $settings = [];

    /**
     * Run a plugin
     *
     * @param string $from
     * @param string $to
     * @return mixed
     */
    public function run($from, $to);

    /**
     * Gets called when the object is called as a function
     *
     * @param array $settings
     * @return mixed
     */
    public function __invoke(array $settings = [])
    {
        $this->settings = $settings;

        return $this;
    }

}

Change the visibility mode {protected => public}


<?php

/**
 * @author    Aaron Scherer
 * @date      12/11/13
 * @license   http://www.apache.org/licenses/LICENSE-2.0.html Apache License, Version 2.0
 */

namespace Aequasi\Bundle\CacheBundle\Routing\Matcher;

use Symfony\Component\Routing\Matcher\UrlMatcher;
use Aequasi\Bundle\CacheBundle\Service\CacheService;

/**
 * Class CacheUrlMatcher
 *
 * @author Aaron Scherer <aequasi@gmail.com>
 */
class CacheUrlMatcher extends UrlMatcher
{
    /**
     * @var CacheService
     */
    protected $cache;

    /**
     * @param string $pathInfo
     *
     * @return array
     */
    public function match($pathInfo)
    {
        $key = 'route_' . $pathInfo;
        if ($this->cache->contains($key)) {
            return $this->cache->fetch($key);
        }

        $match = parent::match($pathInfo);
        $this->cache->save($key, $match, 60 * 60 * 24 * 7);

        return $match;
    }

    /**
     * @param CacheService $cache
     */
    public function setCache($cache)
    {
        $this->cache = $cache;
    }

    /**
     * @return CacheService
     */
    public function getCache()
    {
        return $this->cache;
    }
}

<?php

/**
 * @author    Aaron Scherer
 * @date      12/11/13
 * @license   http://www.apache.org/licenses/LICENSE-2.0.html Apache License, Version 2.0
 */

namespace Aequasi\Bundle\CacheBundle\Routing\Matcher;

use Symfony\Component\Routing\Matcher\UrlMatcher;
use Aequasi\Bundle\CacheBundle\Service\CacheService;

/**
 * Class CacheUrlMatcher
 *
 * @author Aaron Scherer <aequasi@gmail.com>
 */
class CacheUrlMatcher extends UrlMatcher
{
    /**
     * @var CacheService
     */
    protected $cache;

    /**
     * @param string $pathInfo
     *
     * @return array
     */
    public function match($pathInfo)
    {
        $key = 'route_' . strtolower($this->context->getMethod()) . '_' . $pathInfo;
        if ($this->cache->contains($key)) {
            return $this->cache->fetch($key);
        }

        $match = parent::match($pathInfo);
        $this->cache->save($key, $match, 60 * 60 * 24 * 7);

        return $match;
    }

    /**
     * @param CacheService $cache
     */
    public function setCache($cache)
    {
        $this->cache = $cache;
    }

    /**
     * @return CacheService
     */
    public function getCache()
    {
        return $this->cache;
    }
}

Add the http method to the route caching key to make it work with FOSRestBundle


<?php
return function(MongoDB $db) {
    $collection = $db->holes;

    $findOne = function($id) use($collection) {
        $hole = null;
        try {
            $hole = $collection->findOne(['_id' => new MongoID($id)]);
        } catch (Exception $e) {
        }

        if ($hole === null) {
            throw new Exception("Hole '{$id}' does not exist.");
        }

        return $hole;
    };

    return [
        'find' => function(array $conditions = array()) use($collection) {
            return iterator_to_array($collection->find($conditions));
        },
        'findOne' => $findOne,
        'addSubmission' => function($id, $username, $submission)  use($collection, $findOne) {
            $hole = $findOne($id);
            $result = \Codegolf\judge(\Codegolf\loadHole($hole['fileName']), \Codegolf\createImage('php-5.5', $submission));
            $result['_id'] = new MongoID();
            $result['username'] = $username;
            $collection->update(['_id' => new MongoID($id)], ['$push' => ['submissions' => $result]]);
        },
    ];
};

<?php
return function(MongoDB $db) {
    $collection = $db->holes;

    $findOne = function($id) use($collection) {
        $hole = null;
        try {
            $hole = $collection->findOne(['_id' => new MongoID($id)]);
        } catch (Exception $e) {
        }

        if ($hole === null) {
            throw new Exception("Hole '{$id}' does not exist.");
        }

        return $hole;
    };

    return [
        'find' => function(array $conditions = array()) use($collection) {
            return iterator_to_array($collection->find($conditions));
        },
        'findOne' => $findOne,
        'addSubmission' => function($id, $username, $submission)  use($collection, $findOne) {
            $hole = $findOne($id);
            $result = \Codegolf\judge(\Codegolf\loadHole($hole['fileName']), \Codegolf\createImage('php-5.5', $submission));
            $result['_id'] = new MongoID();
            $result['username'] = $username;

            $code = file_get_contents($submission);
            $result['code'] = utf8_encode($code);
            $result['length'] = strlen($code);

            $collection->update(['_id' => new MongoID($id)], ['$push' => ['submissions' => $result]]);
        },
    ];
};

Add source code and length to submissions.

Have to utf8_encode the source because it can be non-ascii.


<?php
namespace autoauth;

$config = require('config.php');

$class = new \ReflectionClass($config->hook->class);
if(!$class->isSubclassOf(hooks\IHook::class))
	return http_response_code(500);

$hook = $class->newInstanceArgs($config->hook->args);

$layout = new layout\Page("pages/index.{$hook->userRole()}.xml");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
	switch($hook->userRole())
	{
	case 'admin':
		$name = $_POST['name'];
		break;

	case 'user':
		$name = $hook->userName();
		break;

	default:
		return;
	}

	$out = $layout->{'//html:input[@readonly]'}->item(0);

	if(!strlen($name))
		$out->setAttribute('value', 'Username cannot be empty!');
	else
	{
		//TODO
		$out->setAttribute('value', "UUID for '$name'");
	}
}

$layout->display();

<?php
namespace autoauth;

$config = require('config.php');

$class = new \ReflectionClass($config->hook->class);
if(!$class->isSubclassOf(hooks\IHook::class))
	return http_response_code(500);

$hook = $class->newInstanceArgs($config->hook->args);

$layout = new layout\Page("pages/index.{$hook->userRole()}.xml");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
	switch($hook->userRole())
	{
	case 'admin':
		$name = $_POST['name'];
		break;

	case 'user':
		$name = $hook->userName();
		break;
	}
}

if(isset($name))
{
	$out = $layout->{'//html:input[@readonly]'}->item(0);

	if(!strlen($name))
		$out->setAttribute('value', 'Username cannot be empty!');
	else
	{
		//TODO
		$out->setAttribute('value', "UUID for '$name'");
	}
}

$layout->display();

Handle the guest-POST case better

Handle the guest-POST case better