<?php

declare(strict_types=1);

namespace SAML2\XML;

use DOMElement;

/**
 * Abstract class to be implemented by all the classes in this namespace
 *
 * @author Tim van Dijen, <tvdijen@gmail.com>
 * @package SimpleSAMLphp
 */

abstract class AbstractConvertable
{
    /**
     * Output the class as an XML-formatted string
     *
     * @return string
     */
    public function __toString(): string
    {
        $xml = $this->toXML();
        return $xml->ownerDocument->saveXML($xml);
    }

    /**
     * Create XML from this class
     *
     * @param \DOMElement|null $parent
     * @return \DOMElement
     */
    abstract public function toXML(DOMElement $parent = null): DOMElement;

    /**
     * Create a class from XML
     *
     * @param \DOMElement $xml
     * @return self
     */
    abstract public static function fromXML(DOMElement $xml): object;
}

<?php

declare(strict_types=1);

namespace SAML2\XML;

use DOMElement;

/**
 * Abstract class to be implemented by all the classes in this namespace
 *
 * @author Tim van Dijen, <tvdijen@gmail.com>
 * @package SimpleSAMLphp
 */

abstract class AbstractConvertable
{
    /**
     * Output the class as an XML-formatted string
     *
     * @return string
     */
    public function __toString(): string
    {
        $xml = $this->toXML();
        return $xml->ownerDocument->saveXML($xml);
    }

    /**
     * Create XML from this class
     *
     * @param \DOMElement|null $parent
     * @return \DOMElement
     */
    abstract public function toXML(DOMElement $parent = null): DOMElement;

    /**
     * Create a class from XML
     *
     * @param \DOMElement|null $xml
     * @return self|null
     */
    abstract public static function fromXML(?DOMElement $xml): ?object;
}

Allow null being passed to fromXML

Allow null being passed to fromXML


<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Swat/SwatReplicableFieldset.php';

/**
 * A fieldset container that replicates itself and its children
 *
 * This is a deprecated alias of {@link SwatReplicableFieldset}.
 *
 * @package    Swat
 * @copyright  2005-2006 silverorange
 * @license    http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 * @deprecated Use SwatReplicableFieldset instead.
 * @see        SwatReplicableFieldset
 */
class SwatReplicatorFieldset extends SwatReplicableFieldset
{
}

?>

<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Swat/SwatReplicableFieldset.php';

/**
 * A fieldset container that replicates itself and its children
 *
 * This is a deprecated alias of {@link SwatReplicableFieldset}.
 *
 * @package    Swat
 * @copyright  2005-2006 silverorange
 * @license    http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 * @deprecated This class was renamed. Use SwatReplicableFieldset instead.
 * @see        SwatReplicableFieldset
 */
class SwatReplicatorFieldset extends SwatReplicableFieldset
{
}

?>

Add explaination to deprecated tag.

Add explaination to deprecated tag.

svn commit r13630


<?php

namespace Helge\Tests;

use Helge\Loader\JsonLoader;

class JsonLoaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Helge\Loader\JsonLoader
     */
    protected $jsonLoader;

    public function setup()
    {

        require 'vendor/autoload.php';

        $this->jsonLoader = new JsonLoader();

    }

    // TODO(22 okt 2015) ~ Helge: Write tests

}

<?php

namespace Helge\Tests;

use Helge\Loader\JsonLoader;

class JsonLoaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * This test ensures that the Load function of the JsonLoader returns a non-empty array when loading the bundled servers.son
     */
    public function testJsonLoaderLoad()
    {
        $loader = new JsonLoader("src/data/servers.json");
        $this->assertNotEmpty($loader->load());
    }

    /**
     * This test checks that the Load function returns false if it has not been provided a path
     */
    public function testJsonLoaderNoPath()
    {
        $loader = new JsonLoader();
        $this->assertFalse($loader->load());
    }

    /**
     * This test checks that the Load function returns false if the file in the provided path does not exist
     */
    public function testJsonLoaderFileNotExist()
    {
        $loader = new JsonLoader('src/data/file_that_does_not_exist.json');
        $this->assertFalse($loader->load());
    }

    /**
     * This test covers the accessors and mutators of the path property
     */
    public function testJsonLoaderGetAndSet()
    {
        $loader = new JsonLoader("src/data/construction_value");
        $this->assertEquals(
            "src/data/construction_value",
            $loader->getPath(),
            'getPath() did not return the value that the loader was instantiated with'
        );

        $loader->setPath("src/data/set_value");
        $this->assertEquals(
            "src/data/set_value",
            $loader->getPath(),
            'getPath() did not return the value provided to setPath()'
        );
    }
}

Add test coverage of JsonLoader

Add test coverage of JsonLoader


<?php

namespace OdinsHat\EuTyreLabel;

class Tyre
{
    public function __construct()
    {

    }
}

<?php

namespace OdinsHat\EuTyreLabel;

class Tyre
{
    private $fuel;
    private $wet;
    private $noiseDb;
    private $noiseClass;

    public function __construct(string $fuel, string $wet, integer $noiseDb, integer $noiseClass)
    {

    }
}

Create basic contructor in tyre

Create basic contructor in tyre


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Affiliate / Controller
 */

namespace PH7;

use PH7\Framework\Url\Header;

class RouterController extends Controller
{
    /**
     * Set the reference to the visitor.
     *
     * @return void
     */
    public function refer()
    {
        if ($this->httpRequest->getExists('aff')) {
            if ((new ExistsCoreModel)->username($this->httpRequest->get('aff'), DbTableName::AFFILIATE)) {
                (new Affiliate)->addRefer($this->httpRequest->get('aff'));
            }
        }

        $this->redirectToWebsite();
    }

    /**
     * Redirect the user to the website's homepage or a specific page if GET 'action' is specified.
     *
     * @return void
     */
    private function redirectToWebsite()
    {
        $sUrl = $this->registry->site_url . $this->httpRequest->get('action');
        Header::redirect($sUrl);
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2019, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Affiliate / Controller
 */

namespace PH7;

use PH7\Framework\Url\Header;

class RouterController extends Controller
{
    /**
     * Set the reference to the visitor.
     *
     * @return void
     */
    public function refer()
    {
        if ($this->httpRequest->getExists('aff')) {
            $this->addUsernameReferer();
        }

        $this->redirectToWebsite();
    }

    private function addUsernameReferer()
    {
        if ((new ExistsCoreModel)->username($this->httpRequest->get('aff'), DbTableName::AFFILIATE)) {
            (new Affiliate)->addRefer($this->httpRequest->get('aff'));
        }
    }

    /**
     * Redirect the user to the website's homepage or a specific page if GET 'action' is specified.
     *
     * @return void
     */
    private function redirectToWebsite()
    {
        $sUrl = $this->registry->site_url . $this->httpRequest->get('action');
        Header::redirect($sUrl);
    }
}

[Readability] Add separated method that adds user referer into DB


<?php

namespace Djebbz\TicketBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Djebbz\TicketBundle\Model\TicketQuery;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render(
            'DjebbzTicketBundle:Default:index.html.twig',
            array('content' => 'Test content')
        );
    }

    public function showAllTicketAction()
    {
        $tickets = TicketQuery::create()
            ->find();

        if (!$tickets) {
            throw $this->createNotFoundException(
                'Sorry, no tickets found. You can create one !'
            );
        }

        return $this->render(
            'DjebbzTicketBundle:Default:showAll.html.twig',
            array('tickets' => $tickets)
        );
    }
}

<?php

namespace Djebbz\TicketBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Djebbz\TicketBundle\Model\TicketQuery;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render(
            'DjebbzTicketBundle:Default:index.html.twig',
            array('content' => 'Test content')
        );
    }

    public function showAllTicketAction()
    {
        $tickets = TicketQuery::create()
            ->find();

        if (!$tickets) {
            throw $this->createNotFoundException(
                'No tickets found.'
            );
        }

        $message = '';

        if (0 === count($tickets)) {
            $message = 'Sorry, no tickets at all. Be the first to create one !';
        }

        return $this->render(
            'DjebbzTicketBundle:Default:showAll.html.twig',
            array(
                'tickets' => $tickets,
                'message' => $message,
            )
        );
    }
}

Print a message when there's no ticket in db


<?php

namespace Kunstmaan\ArticleBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class AbstractAuthorAdminType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', null, array(
            'label' => 'article.author.form.name.label',
        ));
        $builder->add('link', null, array(
            'label' => 'article.author.form.link.label',
        ));
    }

    function getBlockPrefix()
    {
        return "abstactauthor_form";
    }

}

<?php

namespace Kunstmaan\ArticleBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class AbstractAuthorAdminType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', null, array(
            'label' => 'article.author.form.name.label',
        ));
        $builder->add('link', null, array(
            'label' => 'article.author.form.link.label',
        ));
    }

    public function getBlockPrefix()
    {
        return "abstactauthor_form";
    }

}

Add public visibility to constructors

Add public visibility to constructors


<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->index('is_locked');
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) {
            $table->dropIndex(['is_locked']);
        });
    }
];

<?php

/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Database\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->index('is_locked');

            Migration::fixIndexNames($schema, $table);
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('discussions', function (Blueprint $table) use ($schema) {
            $table->dropIndex(['is_locked']);

            Migration::fixIndexNames($schema, $table);
        });
    }
];

Fix index names in migrations

Fix index names in migrations

This can be reverted when we upgrade to Laravel 5.7.


<?php
namespace RpsCompetition\Db;

if (!class_exists('AVH_RPS_Client')) {
    header('Status: 403 Forbidden');
    header('HTTP/1.1 403 Forbidden');
    exit();
}

/**
 * Class QueryBanquet
 *
 * @author    Peter van der Does
 * @copyright Copyright (c) 2015, AVH Software
 * @package   RpsCompetition\Db
 */
class QueryBanquet
{
    private $rpsdb;

    /**
     * Constructor
     *
     * @param RpsDb $rpsdb
     */
    public function __construct(RpsDb $rpsdb)
    {
        $this->rpsdb = $rpsdb;
    }

    /**
     * Get the banquets between the given dates
     *
     * @param string $season_start_date
     * @param string $season_end_date
     *
     * @return array
     */
    public function getBanquets($season_start_date, $season_end_date)
    {
        $sql = $this->rpsdb->prepare(
            "SELECT *
		FROM competitions
		WHERE Competition_Date >= %s AND
		  Competition_Date < %s AND
		  Theme LIKE %s
		ORDER BY ID",
            $season_start_date,
            $season_end_date,
            '%banquet%'
        )
        ;
        $return = $this->rpsdb->get_results($sql, ARRAY_A);

        return $return;
    }
}

<?php
namespace RpsCompetition\Db;

if (!class_exists('AVH_RPS_Client')) {
    header('Status: 403 Forbidden');
    header('HTTP/1.1 403 Forbidden');
    exit();
}

/**
 * Class QueryBanquet
 *
 * @author    Peter van der Does
 * @copyright Copyright (c) 2015, AVH Software
 * @package   RpsCompetition\Db
 */
class QueryBanquet
{
    private $rpsdb;

    /**
     * Constructor
     *
     * @param RpsDb $rpsdb
     */
    public function __construct(RpsDb $rpsdb)
    {
        $this->rpsdb = $rpsdb;
    }

    /**
     * Get the banquets between the given dates
     *
     * @param string $season_start_date
     * @param string $season_end_date
     *
     * @return array
     */
    public function getBanquets($season_start_date, $season_end_date)
    {
        $sql = $this->rpsdb->prepare(
            'SELECT *
		FROM competitions
		WHERE Competition_Date >= %s AND
		  Competition_Date < %s AND
		  Theme LIKE %s
		ORDER BY ID',
            $season_start_date,
            $season_end_date,
            '%banquet%'
        )
        ;
        $return = $this->rpsdb->get_results($sql, ARRAY_A);

        return $return;
    }
}

Replace double quotes with single quotes


<?php

class Home extends CI_Controller {

  public function index() {
    if($this->check_admin() === true){

      $data['title'] = 'Admin Panel';

      $this->load->view('general/header', $data);
      $this->load->view('admin/index', $data);
      $this->load->view('general/footer');

    }
  }

  public function update_items() {
    if($this->check_admin() === true){

      $this->config->load('craftshop');
      $itemapi_cfg = $this->config->item('itemapi');
      $this->load->library('itemapi', $itemapi_cfg);
      $this->load->model('minecraftitem_model', 'mcitems');

      $data['urls'] = $this->itemapi->getUrls();
      $data['update'] = $this->itemapi->getList(true);

      $updated = $this->mcitems->apply_update($data['update']->data->data);

      $data['updated'] = $updated;
      $data['title'] = 'Update Items';
      $this->load->view('general/header', $data);
      $this->load->view('admin/update_items', $data);
      $this->load->view('general/footer');

    }
  }

}

?>

<?php

class Home extends MY_Controller {

  public function index() {
    if($this->check_admin() === true){

      $data['title'] = 'Admin Panel';

      $this->load->view('general/header', $data);
      $this->load->view('admin/index', $data);
      $this->load->view('general/footer');

    }
  }

  public function update_items() {
    if($this->check_admin() === true){

      $this->config->load('craftshop');
      $itemapi_cfg = $this->config->item('itemapi');
      $this->load->library('itemapi', $itemapi_cfg);
      $this->load->model('minecraftitem_model', 'mcitems');

      $data['urls'] = $this->itemapi->getUrls();
      $data['update'] = $this->itemapi->getList(true);

      $updated = $this->mcitems->apply_update($data['update']->data->data);

      $data['updated'] = $updated;
      $data['title'] = 'Update Items';
      $this->load->view('general/header', $data);
      $this->load->view('admin/update_items', $data);
      $this->load->view('general/footer');

    }
  }

}

?>

Change Admin/Home controller parent to MY_Controller to get check_admin() method

Signed-off-by: JWhy <6a9f7c06e789f829524fd1a3a38b8c7d794c3a1f@jwhy.de>


<?php
namespace NamelessCoder\GizzleGitPlugins\GizzlePlugins;

use NamelessCoder\Gizzle\Payload;
use NamelessCoder\Gizzle\PluginInterface;

/**
 * Class ClonePlugin
 */
class ClonePlugin extends AbstractGitPlugin implements PluginInterface {

	/**
	 * @var array
	 */
	protected $settings = array();

	/**
	 * Initialize the plugin with an array of settings.
	 *
	 * @param array $settings
	 * @return void
	 */
	public function initialize(array $settings) {
		$this->settings = $settings;
	}

	/**
	 * Analyse $payload and return TRUE if this plugin should
	 * be triggered in processing the payload.
	 *
	 * @param Payload $payload
	 * @return boolean
	 */
	public function trigger(Payload $payload) {

	}

	/**
	 * Perform whichever task the Plugin should perform based
	 * on the payload's data.
	 *
	 * @param Payload $payload
	 * @return void
	 */
	public function process(Payload $payload) {

	}

}

<?php
namespace NamelessCoder\GizzleGitPlugins\GizzlePlugins;

use NamelessCoder\Gizzle\Payload;
use NamelessCoder\Gizzle\PluginInterface;

/**
 * Class ClonePlugin
 */
class ClonePlugin extends AbstractGitPlugin implements PluginInterface {

	const OPTION_DIRECTORY = 'directory';
	const OPTION_REPOSITORY = 'repository';
	const OPTION_BRANCH = 'branch';
	const OPTION_DEPTH = 'depth';

	/**
	 * @var array
	 */
	protected $settings = array();

	/**
	 * Initialize the plugin with an array of settings.
	 *
	 * @param array $settings
	 * @return void
	 */
	public function initialize(array $settings) {
		$this->settings = $settings;
	}

	/**
	 * Analyse $payload and return TRUE if this plugin should
	 * be triggered in processing the payload.
	 *
	 * @param Payload $payload
	 * @return boolean
	 */
	public function trigger(Payload $payload) {

	}

	/**
	 * Perform whichever task the Plugin should perform based
	 * on the payload's data.
	 *
	 * @param Payload $payload
	 * @return void
	 */
	public function process(Payload $payload) {

	}

}

Add settings for Clone plugin

[TASK] Add settings for Clone plugin


<?php
/*
 * This file is part of the fnacApi.
 * (c) 2011 Fnac
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FnacApiClient\Service\Response;

use Symfony\Component\Serializer\SerializerInterface;

use FnacApiClient\Entity\ShopInvoice;

/**
 * BatchQueryResponse service base definition for batch query response
 *
 * @author     Fnac
 * @version    1.0.0
 */
class ShopInvoiceQueryResponse extends QueryResponse
{
    private $shop_invoices = array();

    /**
     * {@inheritdoc}
     */
    public function denormalize(SerializerInterface $serializer, $data, $format = null)
    {
        parent::denormalize($serializer, $data, $format);

        $this->shop_invoices = new \ArrayObject();
        foreach ($data['shop_invoice'] as $shop_invoice) {
            $shopInvoiceObj = new ShopInvoice();
            $shopInvoiceObj->denormalize($serializer, $shop_invoice, $format);
            $this->shop_invoices[] = $shopInvoiceObj;
        }
    }

    /**
     * List of shops' invoices
     *
     * @see FnacApiClient\Entity\ShopInvoice
     *
     * @return ArrayObject<ShopInvoice>
     */
    public function getShopInvoices()
    {
        return $this->shop_invoices;
    }
}

<?php
/*
 * This file is part of the fnacApi.
 * (c) 2011 Fnac
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FnacApiClient\Service\Response;

use Symfony\Component\Serializer\SerializerInterface;

use FnacApiClient\Entity\ShopInvoice;

/**
 * BatchQueryResponse service base definition for batch query response
 *
 * @author     Fnac
 * @version    1.0.0
 */
class ShopInvoiceQueryResponse extends QueryResponse
{
    private $shop_invoices = array();

    /**
     * {@inheritdoc}
     */
    public function denormalize(SerializerInterface $serializer, $data, $format = null)
    {
        parent::denormalize($serializer, $data, $format);

        $this->shop_invoices = new \ArrayObject();

        if(!empty($data['shop_invoice'])) {
            foreach ($data['shop_invoice'] as $shop_invoice) {
                $shopInvoiceObj = new ShopInvoice();
                $shopInvoiceObj->denormalize($serializer, $shop_invoice, $format);
                $this->shop_invoices[] = $shopInvoiceObj;
            }
        }
    }

    /**
     * List of shops' invoices
     *
     * @see FnacApiClient\Entity\ShopInvoice
     *
     * @return ArrayObject<ShopInvoice>
     */
    public function getShopInvoices()
    {
        return $this->shop_invoices;
    }
}

Fix shop invoice index notice

Fix shop invoice index notice


<?php

namespace LaPoiz\WindBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

//use LaPoiz\WindBundle\Entity\DataWindPrev;
use LaPoiz\WindBundle\core\websiteDataManage\WebsiteGetData;

class GetDataWindguruCommand extends ContainerAwareCommand  {

 	protected function configure()
    {
        $this
            ->setName('lapoiz:getDataWindguru')
            ->setDescription('Get Data from web site: Meteo France')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
		// get list of URL
    	$em = $this->getContainer()->get('doctrine.orm.entity_manager');
    	$dataWindPrevList = $em->getRepository('LaPoizWindBundle:DataWindPrev')->findAll();

    	foreach ($dataWindPrevList as $dataWindPrev) {
            if ($dataWindPrev->getWebSite()->getNom() == WebsiteGetData::windguruName) {
                GetDataCommand::getDataFromDataWindPrev($dataWindPrev, $output, $em);
            }
    	}
    }
}

<?php

namespace LaPoiz\WindBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

//use LaPoiz\WindBundle\Entity\DataWindPrev;
use LaPoiz\WindBundle\core\websiteDataManage\WebsiteGetData;

class GetDataWindguruCommand extends ContainerAwareCommand  {

 	protected function configure()
    {
        $this
            ->setName('lapoiz:getDataWindguru')
            ->setDescription('Get Data from web site: Meteo France')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
		// get list of URL
    	$em = $this->getContainer()->get('doctrine.orm.entity_manager');
    	$dataWindPrevList = $em->getRepository('LaPoizWindBundle:DataWindPrev')->findAll();

    	foreach ($dataWindPrevList as $dataWindPrev) {
            if ($dataWindPrev->getWebSite()->getNom() == WebsiteGetData::windguruName) {
                GetDataCommand::getDataFromDataWindPrev($dataWindPrev, $output, $em);
            }
            if ($dataWindPrev->getWebSite()->getNom() == WebsiteGetData::windguruProName) {
                GetDataCommand::getDataFromDataWindPrev($dataWindPrev, $output, $em);
            }
    	}
    }
}

Add on commande GetDataWindGuru: scan WindGuruPro used on cron


<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        TokenMismatchException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        return parent::render($request, $e);
    }
}

Add TokenMismatchException to the dontReport array


<?php

namespace Liip\RMT\Tests\Functional;

class RMTFunctionalTestBase extends \PHPUnit_Framework_TestCase
{
    protected $tempDir;

    protected function setUp() {

        // Create a temp folder
        $this->tempDir = tempnam(sys_get_temp_dir(),'');
        if (file_exists($this->tempDir)) {
            unlink($this->tempDir);
        }
        mkdir($this->tempDir);
        chdir($this->tempDir);

        // Create the executable task inside
        $rmtDir = realpath(__DIR__.'/../../../../../');
        file_put_contents('RMT', <<<EOF
#!/usr/bin/env php
<?php define('RMT_ROOT_DIR', __DIR__); ?>
<?php require '$rmtDir/command.php'; ?>
EOF
        );
        exec('chmod +x RMT');
    }

    protected function createJsonConfig($generator, $persister, $otherConfig=array()) {
        $allConfig = array_merge($otherConfig, array(
            'version-persister'=>$persister,
            'version-generator'=>$generator
        ));
        file_put_contents('rmt.json', json_encode($allConfig));
    }

    protected function tearDown()
    {
        exec('rm -rf '.$this->tempDir);
    }

    protected function initGit()
    {
        exec('git init');
        exec('git add *');
        exec('git commit -m "First commit"');
    }

    protected function  manualDebug()
    {
        echo "\n\nMANUAL DEBUG Go to:\n > cd ".$this->tempDir."\n\n"; exit();
    }

}

<?php

namespace Liip\RMT\Tests\Functional;

class RMTFunctionalTestBase extends \PHPUnit_Framework_TestCase
{
    protected $tempDir;

    protected function setUp() {

        // Create a temp folder
        $this->tempDir = tempnam(sys_get_temp_dir(),'');
        if (file_exists($this->tempDir)) {
            unlink($this->tempDir);
        }
        mkdir($this->tempDir);
        chdir($this->tempDir);

        // Create the executable task inside
        $rmtDir = realpath(__DIR__.'/../../../../../');
        exec("php $rmtDir/command.php init --generator=basic-increment --persister=vcs-tag --vcs=git");
    }

    protected function createJsonConfig($generator, $persister, $otherConfig=array()) {
        $allConfig = array_merge($otherConfig, array(
            'version-persister'=>$persister,
            'version-generator'=>$generator
        ));
        file_put_contents('rmt.json', json_encode($allConfig));
    }

    protected function tearDown()
    {
        exec('rm -rf '.$this->tempDir);
    }

    protected function initGit()
    {
        exec('git init');
        exec('git add *');
        exec('git commit -m "First commit"');
    }

    protected function  manualDebug()
    {
        echo "\n\nMANUAL DEBUG Go to:\n > cd ".$this->tempDir."\n\n"; exit();
    }

}

Use the init command to setup functionnal tests


<?php

// http://wycks.wordpress.com/2013/02/14/why-the-content_width-wordpress-global-kinda-sucks
$content_width = 90000; // pixels

function getRedirect() {
    $url  = $_SERVER["SERVER_NAME"];
    $url .= $_SERVER["REQUEST_URI"];

    $redirect = preg_replace("/^(.*?)\.(.*)$/","$2", $url);

    return 'http://'.$redirect;
}

function setup() {

	// Enable support for Post Thumbnails on posts and pages.
	add_theme_support( 'post-thumbnails' );

	// Enable support for Post Formats.
	add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link' ) );

}

add_action( 'after_setup_theme', 'setup' );

<?php

// http://wycks.wordpress.com/2013/02/14/why-the-content_width-wordpress-global-kinda-sucks
$content_width = 90000; // pixels

function getRedirect() {
    $url  = $_SERVER["SERVER_NAME"];
    $url .= $_SERVER["REQUEST_URI"];

    $redirect = preg_replace("/^(.*?)\.(.*)$/","$2", $url);

    return 'http://'.$redirect;
}

function setup() {

	// Enable support for Post Thumbnails on posts and pages
	add_theme_support( 'post-thumbnails' );

	// Enable support for Post Formats
	add_theme_support( 'post-formats', array( 'image', 'quote', 'link', 'chat', 'audio', 'video' ) );

}

function api_url() {
    wp_redirect( 'https://www.storyteller.io/apis/wordpress-rest-api' );
}

function customize_menu() {

    // http://justintadlock.com/archives/2011/06/13/removing-menu-pages-from-the-wordpress-admin
    remove_menu_page('edit-comments.php');
    remove_menu_page('themes.php');
    remove_menu_page('tools.php');
    remove_menu_page('plugins.php');

    // http://codex.wordpress.org/Function_Reference/add_menu_page
    add_menu_page( 'API', 'API', 'activate_plugins', 'api', 'api_url', 'dashicons-admin-links', '20.1' );

}

add_action( 'after_setup_theme', 'setup' );
add_action( 'admin_menu', 'customize_menu', 999 );

Customize navigation and post formats

Customize navigation and post formats


<?php

namespace Laravel\Scout\Tests\Fixtures;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class SearchableModelWithSoftDeletes extends Model
{
    use SoftDeletes;
    use Searchable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['published_at'];

    public function shouldBeSearchable()
    {
        return !$this->trashed() && ! is_null($this->published_at);
    }
}

<?php

namespace Laravel\Scout\Tests\Fixtures;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class SearchableModelWithSoftDeletes extends Model
{
    use SoftDeletes;
    use Searchable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['published_at'];

    public function shouldBeSearchable()
    {
        return ! $this->trashed() && ! is_null($this->published_at);
    }
}

Add space after unary operator

Add space after unary operator


<?php

namespace Dock\Doctor;

use Dock\IO\ProcessRunner;

class DnsDock extends Task
{
    /**
     * @var mixed
     */
    private $dnsDockInstaller;

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

    /**
     * @param ProcessRunner $processRunner
     * @param mixed $dnsDockInstaller
     * @param mixed $dockerRouting
     */
    public function __construct(ProcessRunner $processRunner, $dnsDockInstaller, $dockerRouting)
    {
        $this->processRunner = $processRunner;
        $this->dnsDockInstaller = $dnsDockInstaller;
        $this->dockerRouting = $dockerRouting;
    }

    /**
     * {@inheritdoc}
     */
    public function run($dryRun)
    {
        $this->handle(
            "test 0 -lt `docker ps -q --filter=name=dnsdock | wc -l`",
            "It seems dnsdock is not running.",
            "Install and start dnsdock by running: `dock-cli docker:install`",
            $this->dnsDockInstaller,
            $dryRun
        );

        $this->handle(
            "ping -c1 dnsdock.docker",
            "It seems your dns is not set up properly.",
             "Add 172.17.42.1 as one of your DNS servers. `dock-cli docker:install` will try to do that",
            $this->dockerRouting,
            $dryRun
        );
    }
}

<?php

namespace Dock\Doctor;

use Dock\IO\ProcessRunner;
use Dock\Installer\InstallerTask;

class DnsDock extends Task
{
    /**
     * @var InstallerTask $dnsDockInstaller
     */
    private $dnsDockInstaller;

    /**
     * @var InstallerTask $dockerRouting
     */
    private $dockerRouting;

    /**
     * @param ProcessRunner $processRunner
     * @param InstallerTask $dnsDockInstaller
     * @param InstallerTask $dockerRouting
     */
    public function __construct(
        ProcessRunner $processRunner,
        InstallerTask $dnsDockInstaller,
        InstallerTask $dockerRouting)
    {
        $this->processRunner = $processRunner;
        $this->dnsDockInstaller = $dnsDockInstaller;
        $this->dockerRouting = $dockerRouting;
    }

    /**
     * {@inheritdoc}
     */
    public function run($dryRun)
    {
        $this->handle(
            "test 0 -lt `docker ps -q --filter=name=dnsdock | wc -l`",
            "It seems dnsdock is not running.",
            "Install and start dnsdock by running: `dock-cli docker:install`",
            $this->dnsDockInstaller,
            $dryRun
        );

        $this->handle(
            "ping -c1 dnsdock.docker",
            "It seems your dns is not set up properly.",
             "Add 172.17.42.1 as one of your DNS servers. `dock-cli docker:install` will try to do that",
            $this->dockerRouting,
            $dryRun
        );
    }
}

Use slightly better type hinting

Use slightly better type hinting


<?php

namespace Plummer\Calendar;

interface EventInterface
{

}

<?php

namespace Plummer\Calendar;

interface EventInterface
{
	public function getName();

	public function getStartDate();

	public function getEndDate();

	public function getOccurrenceDate();

	public function getParent();
}

Move previous adaptable interface methods into actual Event interface.


<?php

namespace Northstar\Http\Controllers\Web;

use Illuminate\Http\Request;
use DoSomething\Gateway\Gladiator;
use Illuminate\Routing\Controller as BaseController;

class UnsubscribeController extends BaseController
{
    /**
     * Gladiator instance.
     *
     * @var \DoSomething\Gateway\Gladiator
     */
    protected $gladiator;

    /**
     * Create the controller instance.
     *
     * @param \DoSomething\Gateway\Gladiator $gladiator
     */
    public function __construct(Gladiator $gladiator)
    {
        $this->gladiator = $gladiator;
    }

    /**
     * Displays the subscriptions page
     */
    public function getSubscriptions()
    {
        return view('auth.subscriptions');
    }

    /**
     *
     */
    public function postSubscriptions(Request $request)
    {
        dd($this->gladiator);
        // make sure to check that inputs exist.
        dd($request->input('competition'));
    }
}

<?php

namespace Northstar\Http\Controllers\Web;

use Illuminate\Http\Request;
use DoSomething\Gateway\Gladiator;
use Illuminate\Routing\Controller as BaseController;

class UnsubscribeController extends BaseController
{
    /**
     * Gladiator instance.
     *
     * @var \DoSomething\Gateway\Gladiator
     */
    protected $gladiator;

    /**
     * Create the controller instance.
     *
     * @param \DoSomething\Gateway\Gladiator $gladiator
     */
    public function __construct(Gladiator $gladiator)
    {
        $this->gladiator = $gladiator;
    }

    /**
     * Displays the subscriptions page
     */
    public function getSubscriptions()
    {
        return view('auth.subscriptions');
    }

    /**
     *
     */
    public function postSubscriptions(Request $request)
    {
        $user = $request->input('user');
        $competition = $request->input('competition');

        if ($user && $competition) {
            $response = $this->gladiator->unsubscribeUser($user, $competition);
        }
    }
}

Make the call to gladiator to unsubscribe a user


<?php

// Manual 'rewrite' of format atom => rss
// TODO: drop this entirely in a few months
if (@$_GET['format'] == 'atom')
	$_GET['format'] = 'rss';

// Keep session data for 120 days, unless explicit destroy in code
ini_set('session.gc_maxlifetime', 1 * 60 * 60 * 24 * 120);

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(__DIR__ . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();

// we only run the application if this file were NOT included (otherwise, the file was included to access misc functions)
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME']))
{
	$application->run();
}

<?php

// Keep session data for 120 days, unless explicit destroy in code
ini_set('session.gc_maxlifetime', 1 * 60 * 60 * 24 * 120);

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(__DIR__ . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();

// we only run the application if this file were NOT included (otherwise, the file was included to access misc functions)
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME']))
{
	$application->run();
}

Drop manual redirection from Atom to RSS


<?php namespace mitogh;

function random_image_src( $size = 'full' ){
	$sources = random_images_src( $size,  1 );
	$src = '';
	foreach( $sources as $image_src ){
		$src = $image_src;
	}
	return $src;
}

function random_images_src( $size = 'full', $total = 1 ){
	$sources = array();
	$ids = random_images_ids( $total );
	foreach( $ids as $image_id ){
		$src = '';
		$data = wp_get_attachment_image_src( $image_id, $size );
		if( $data && ! empty( $data ) ){
			$src = $data[0];
		}
		$sources[] = $src;
	}
	return $sources;
}

function random_images_ids( $total = 1 ){
	$query = new Query( array(
		'post_mime_type' => 'image',
		'posts_per_page' => (int) $total,
	));
	return $query->run();
}

/* $url = random_image_src(); */
/* printf( '%s', $url, $url); */
/* printf( '', $url ); */
/* die(); */

Add basic example of usage

Add basic example of usage


<?php

/*
 * Show debug code.
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * Load Composer requirements.
 */
require 'vendor/autoload.php';

/*
 * Establish our routing table.
 */
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';
$router['bounce'] = 'bounce';

/*
 * Identify which method is being requested, and whether any parameters are being passed to that
 * method.
 */
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{

	$tmp = explode('/', $method);
	$method = $tmp[0];
	if (!empty($tmp[1]))
	{
		$parameter = $tmp[1];
	}

}

/*
 * If our method is invalid, fail with a 404.
 */
if ( ($method === FALSE) || !isset($router[$method]) )
{

	header("HTTP/1.0 404 Not Found");
	echo '404 Not Found';
	exit();

}

/*
 * Enable cross-origin resource sharing (CORS).
 */
header("Access-Control-Allow-Origin: *");

/*
 * Pass off the request to the relevant router.
 */
include '../includes/' . $router[$method] . '.inc.php';

<?php

/*
 * Show debug code.
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * Load Composer requirements.
 */
require 'vendor/autoload.php';

/*
 * Establish our routing table.
 */
$router = array();
$router['registrars'] = 'registrars';
$router['validator'] = 'validator';
$router['submit'] = 'submit';
$router['bounce'] = 'bounce';

/*
 * Identify which method is being requested, and whether any parameters are being passed to that
 * method.
 */
$url_components = parse_url($_SERVER['REQUEST_URI']);
$method = str_replace('/api/', '', $url_components['path']);
if (strpos($method, '/') !== FALSE)
{

	$tmp = explode('/', $method);
	$method = $tmp[0];
	if (!empty($tmp[1]))
	{
		$parameter = $tmp[1];
	}

}

/*
 * If our method is invalid, fail with a 404.
 */
if ( ($method === FALSE) || !isset($router[$method]) )
{

	header("HTTP/1.0 404 Not Found");
	echo '404 Not Found';
	exit();

}

/*
 * Enable cross-origin resource sharing (CORS).
 */
header("Access-Control-Allow-Origin: *");

/*
 * Pass off the request to the relevant router.
 */
include 'includes/' . $router[$method] . '.inc.php';

Load includes from within the api directory


<?php

Git::$repositories['Gatekeeper'] = [
    'remote' => 'git@github.com:JarvusInnovations/Gatekeeper.git',
    'originBranch' => 'master',
    'workingBranch' => 'instances/' . Site::getConfig('primary_hostname'),
    'localOnly' => true,
    'trees' => [
        'dwoo-plugins',
        'event-handlers',
        'html-templates',
        'php-classes',
        'php-config' => [
            'exclude' => '#^/Git\\.config\\.php$#' // don't sync this file
        ],
        'php-migrations',
        'phpunit-tests',
        'sencha-workspace/pages',
        'site-root' => [
            'exclude' => [
                '#^/css(/|$)#', // don't sync /css, this directory is generated by /sass/compile
                '#^/js/pages(/|$)#' // don't sync /js/pages, this directory is generated by /sencha-cmd/pages-build
            ]
        ]
    ]
];

Git::$repositories['symfony-yaml'] = [
    'remote' => 'https://github.com/symfony/Yaml.git',
    'originBranch' => 'master',
    'workingBranch' => 'master',
    'trees' => [
        'php-classes/Symfony/Component/Yaml' => [
            'path' => '.',
            'exclude' => [
                '#\\.gitignore$#',
                '#^/Tests#',
                '#\\.md$#',
                '#composer\\.json#',
                '#phpunit\\.xml\\.dist#'
            ]
        ]
    ]
];

Git::$repositories['jarvus-highlighter'] = [
    'remote' => "https://github.com/JarvusInnovations/jarvus-highlighter.git",
    'originBranch' => 'master',
    'workingBranch' => 'master',
    'trees' => [
        "sencha-workspace/packages/jarvus-highlighter" => '.'
    ]
];

<?php

Git::$repositories['Gatekeeper'] = [
    'remote' => 'git@github.com:JarvusInnovations/Gatekeeper.git',
    'originBranch' => 'master',
    'workingBranch' => 'instances/' . Site::getConfig('primary_hostname'),
    'localOnly' => true,
    'trees' => [
        'dwoo-plugins',
        'event-handlers',
        'html-templates',
        'php-classes',
        'php-config' => [
            'exclude' => '#^/Git\\.config\\.php$#' // don't sync this file
        ],
        'php-migrations',
        'phpunit-tests',
        'sencha-workspace/pages',
        'site-root' => [
            'exclude' => [
                '#^/css(/|$)#', // don't sync /css, this directory is generated by /sass/compile
                '#^/js/pages(/|$)#' // don't sync /js/pages, this directory is generated by /sencha-cmd/pages-build
            ]
        ]
    ]
];

Git::$repositories['jarvus-highlighter'] = [
    'remote' => "https://github.com/JarvusInnovations/jarvus-highlighter.git",
    'originBranch' => 'master',
    'workingBranch' => 'master',
    'trees' => [
        "sencha-workspace/packages/jarvus-highlighter" => '.'
    ]
];

Remove symfony-yaml repo link, it's been merged into skeleton-v1


<?php
/**
 * @title            Entity Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Mvc / Model / Engine
 * @version          1.0
 */

namespace PH7\Framework\Mvc\Model\Engine;

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

abstract class Entity
{
    /**
     * @var integer
     */
    private $_iId;

    /**
     * Get the primary key.
     *
     * @return integer
     */
    public function getKeyId()
    {
        $this->checkKeyId();

        return $this->_iId;
    }

    /**
     * Set the primary key.
     *
     * @param integer $iId
     *
     * @return void
     */
    public function setKeyId($iId)
    {
        $this->_iId = (int)$iId;
    }

    /**
     * Check if the $_iId attribute is not empty, otherwise we set the last insert ID.
     *
     * @see Db::lastInsertId()
     *
     * @return void
     */
    protected function checkKeyId()
    {
        if (empty($this->_iId)) {
            $this->setKeyId(Db::getInstance()->lastInsertId());
        }
    }
}

<?php
/**
 * @title            Entity Class
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Mvc / Model / Engine
 * @version          1.0
 */

namespace PH7\Framework\Mvc\Model\Engine;

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

abstract class Entity
{
    /**
     * @var int
     */
    private $iId;

    /**
     * Get the primary key.
     *
     * @return int
     */
    public function getKeyId()
    {
        $this->checkKeyId();

        return $this->iId;
    }

    /**
     * Set the primary key.
     *
     * @param int $iId
     *
     * @return void
     */
    public function setKeyId($iId)
    {
        $this->iId = (int)$iId;
    }

    /**
     * Check if the $_iId attribute is not empty, otherwise we set the last insert ID.
     *
     * @see Db::lastInsertId()
     *
     * @return void
     */
    protected function checkKeyId()
    {
        if (empty($this->iId)) {
            $this->setKeyId(Db::getInstance()->lastInsertId());
        }
    }
}

Remove underscore _ from private members (was old Pear coding conventions for PHP4+) + update phpdoc type names


<?php

namespace App\Modules\System\Providers;

use App\Modules\System\Models\Option;

use Nova\Support\Facades\Cache;
use Nova\Support\Facades\Config;
use Nova\Support\ServiceProvider;

class SystemServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the Application Events.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadOptions();
    }

    /**
     * Register the System module Service Provider.
     *
     * This service provider is a convenient place to register your modules
     * services in the IoC container. If you wish, you may make additional
     * methods or service providers to keep the code more focused and granular.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Load the options from database.
     *
     * @return void
     */
    protected function loadOptions()
    {
        $options = Cache::remember('system_options', 1440, function()
        {
            return Option::all();
        });

        foreach ($options as $option) {
            $key = $option->group .'.' .$option->item;

            Config::set($key, $option->value);
        }
    }

}

<?php

namespace App\Modules\System\Providers;

use App\Modules\System\Models\Option;

use Nova\Support\Facades\Cache;
use Nova\Support\Facades\Config;
use Nova\Support\ServiceProvider;

class SystemServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the Application Events.
     *
     * @return void
     */
    public function boot()
    {
        if (! $this->runningInConsole()) {
            $this->loadOptions();
        }
    }

    /**
     * Register the System module Service Provider.
     *
     * This service provider is a convenient place to register your modules
     * services in the IoC container. If you wish, you may make additional
     * methods or service providers to keep the code more focused and granular.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Load the options from database.
     *
     * @return void
     */
    protected function loadOptions()
    {
        $options = Cache::remember('system_options', 1440, function()
        {
            return Option::all();
        });

        foreach ($options as $option) {
            $key = $option->group .'.' .$option->item;

            Config::set($key, $option->value);
        }
    }

    /**
     * Determine if we are running in the console.
     *
     * @return bool
     */
    protected function runningInConsole()
    {
        return $this->app->runningInConsole();
    }
}

Add the options to configuration only when not running on console


<?php

/**
 * PHP Version 5.3
 *
 * @copyright   (c) 2015 brian ridley
 * @author      brian ridley <ptlis@ptlis.net>
 * @license     http://opensource.org/licenses/MIT MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ptlis\ShellCommand\Test\Integration\Environment;

use ptlis\ShellCommand\WindowsEnvironment;

class WindowsEnvironmentTest extends \PHPUnit_Framework_TestCase
{
    public function testFullyQualified()
    {
        $command = __DIR__ . '/../../commands/windows/test.bat';

        $env = new WindowsEnvironment();

        if (!in_array(PHP_OS, $env->getSupportedList())) {
            $this->markTestSkipped('Tests requires Windows operating system');
        }

        $valid = $env->validateCommand($command);

        $this->assertSame(true, $valid);
    }
}

<?php

/**
 * PHP Version 5.3
 *
 * @copyright   (c) 2015 brian ridley
 * @author      brian ridley <ptlis@ptlis.net>
 * @license     http://opensource.org/licenses/MIT MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ptlis\ShellCommand\Test\Integration\Environment;

use ptlis\ShellCommand\WindowsEnvironment;

class WindowsEnvironmentTest extends \PHPUnit_Framework_TestCase
{
    public function testFullyQualified()
    {
        $command = __DIR__ . '\..\..\commands\windows\test.bat';

        $env = new WindowsEnvironment();

        if (!in_array(PHP_OS, $env->getSupportedList())) {
            $this->markTestSkipped('Tests requires Windows operating system');
        }

        $valid = $env->validateCommand($command);

        $this->assertSame(true, $valid);
    }

    public function testRelative()
    {
        $command = 'tests\commands\windows\test.bat';

        $env = new WindowsEnvironment();

        if (!in_array(PHP_OS, $env->getSupportedList())) {
            $this->markTestSkipped('Tests requires Windows operating system');
        }

        $valid = $env->validateCommand($command);

        $this->assertSame(true, $valid);
    }
}

Add test for relative paths in Windows

Add test for relative paths in Windows


<?php

namespace Gitonomy\Bundle\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use Gitonomy\Bundle\CoreBundle\Entity\User;

/**
 * Base class for every controller of the frontend.
 *
 * @author Alexandre Salomé <alexandre.salome@gmail.com>
 */
class BaseController extends Controller
{
    /**
     * Checks the current security context grants a given role.
     *
     * @param string $permission The permission to check (can be an array, meaning OR)
     * @param string $message An error message (internal, will not be displayed
     */
    protected function assertPermission($permission, $message = 'Access Denied')
    {
        $user = $this->getUser();

        if (!$user instanceof User || !$this->get('gitonomy_frontend.security.right')->isGranted($user, $permission)) {
            throw new AccessDeniedException($message);
        }
    }
}

<?php

namespace Gitonomy\Bundle\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use Gitonomy\Bundle\CoreBundle\Entity\User;
use Gitonomy\Bundle\CoreBundle\Entity\Project;

/**
 * Base class for every controller of the frontend.
 *
 * @author Alexandre Salomé <alexandre.salome@gmail.com>
 */
class BaseController extends Controller
{
    /**
     * Checks the current security context grants a given role.
     *
     * @param string $permission The permission to check (can be an array, meaning OR)
     * @param string $message An error message (internal, will not be displayed)
     */
    protected function assertPermission($permission, $message = 'Access Denied')
    {
        $user = $this->getUser();

        if (!$user instanceof User || !$this->get('gitonomy_frontend.security.right')->isGranted($user, $permission)) {
            throw new AccessDeniedException($message);
        }
    }

    /**
     * Checks the current security context grants a given role to the user for a project.
     *
     * @param Gitonomy\Bundle\CoreBundle\Entity\Project $project The project to check
     * @param mixed $permission A permission name (or an array, meaning OR)
     * @param string $message An error message (internal, will not be displayed)
     */
    protected function assertProjectPermission(Project $project, $permission, $message = 'Access Denied')
    {
        $user = $this->getUser();

        if (!$user instanceof User || !$this->get('gitonomy_frontend.security.right')->isGrantedForProject($user, $project, $permission)) {
            throw new AccessDeniedException($message);
        }
    }
}

Add a base method to check permissions against a project


<?php

namespace Blog\FrontendBundle\Controller;

use Blog\DomainBundle\Service\PostService;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class PostController extends Controller
{
	/**
	 * @Template()
	 * @return array
	 */
	public function indexAction()
	{
		return array('posts' => $this->getPostService()->getAllPosts());
	}

	/**
	 * @Template()
	 * @param int $id
	 * @return array
	 */
	public function viewAction($id)
	{
		return array('post' => $this->getPostService()->getPost($id));
	}

	/**
	 * @return PostService
	 */
	private function getPostService()
	{
		return $this->get('domain.service.post');
	}
}

<?php

namespace Blog\FrontendBundle\Controller;

use Blog\DomainBundle\Service\PostService;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class PostController extends Controller
{
	/**
	 * @Template()
	 * @return array
	 */
	public function indexAction()
	{
		return array('posts' => $this->getPostService()->getAllPosts());
	}

	/**
	 * @Template()
	 * @param int $id
	 * @return array
	 */
	public function viewAction($id)
	{
		return array('post' => $this->getPostService()->getPost($id));
	}

	/**
	 * @return PostService
	 */
	private function getPostService()
	{
		return $this->get('blog.domain.service.post');
	}
}

Fix name of service in controller

Fix name of service in controller


<?php

namespace Kula\Core\Bundle\FrameworkBundle\EventListener;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

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

class AuthenticatedUserListener implements EventSubscriberInterface {
  private $router;
  private $container;

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

  public static function getSubscribedEvents() {
    return array(
      KernelEvents::REQUEST => array('onKernelRequest', 0),
    );
  }

  public function onKernelRequest(GetResponseEvent $event) {

    if ($this->container->get('session')->get('user_id') > 0 AND $this->container->get('session')->get('portal') == 'core' ) {
      $routeName = $this->container->get('request')->get('_route');
      if ($routeName != 'core_home' AND $routeName == 'top') {
        $event->setResponse(new RedirectResponse($this->router->generate('sis_home')));
      }
    }

  }
}

<?php

namespace Kula\Core\Bundle\FrameworkBundle\EventListener;

use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

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

class AuthenticatedUserListener implements EventSubscriberInterface {
  private $router;
  private $container;

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

  public static function getSubscribedEvents() {
    return array(
      KernelEvents::REQUEST => array('onKernelRequest', 0),
    );
  }

  public function onKernelRequest(GetResponseEvent $event) {

    if ($this->container->get('session')->get('user_id') > 0 AND $this->container->get('session')->get('portal') == 'core' ) {
      $routeName = $this->container->get('request_stack')->getCurrentRequest()->get('_route');
      if ($routeName != 'core_home' AND $routeName == 'top') {
        $event->setResponse(new RedirectResponse($this->router->generate('sis_home')));
      }
    }

  }
}

Fix use of request service.

Fix use of request service.


<?php

namespace Oro\Bundle\TestFrameworkBundle\Test\Form;

use \Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MutableFormEventSubscriber implements EventSubscriberInterface
{

 protected static $events = [];

    protected $wrapped;

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

    public static function getSubscribedEvents()
    {
        return self::$events;
    }

    public static function setSubscribedEvents($events)
    {
        self::$events = $events;
    }

    public function __call($method, $args)
    {
        if (!method_exists($this->wrapped, $method)) {
            throw new Exception("unknown method [$method]");
        }

        return call_user_func_array(
            array($this->wrapped, $method),
            $args
        );
    }
}

<?php

namespace Oro\Bundle\TestFrameworkBundle\Test\Form;

use \Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Allows to mock static getSubscribedEvents() function of event listener class
 * Basically should be used with PHPUnit4 as replacement of mockStatic
 */
class MutableFormEventSubscriber implements EventSubscriberInterface
{
    /** @var array */
    protected static $events = [];

    /** @var \Symfony\Component\EventDispatcher\EventSubscriberInterface */
    protected $wrapped;

    /**
     * @param \Symfony\Component\EventDispatcher\EventSubscriberInterface $wrapped
     */
    public function __construct(EventSubscriberInterface $wrapped)
    {
        $this->wrapped = $wrapped;
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return self::$events;
    }

    /**
     * @param array $events
     */
    public static function setSubscribedEvents(array $events)
    {
        self::$events = $events;
    }

    /**
     * @param $method
     * @param $args
     *
     * @throws \RuntimeException
     * @return mixed
     */
    public function __call($method, $args)
    {
        if (!method_exists($this->wrapped, $method)) {
            throw new \RuntimeException(sprintf('Unknown method %s', $method));
        }

        return call_user_func_array(
            array($this->wrapped, $method),
            $args
        );
    }
}

BAP-5213: Remove staticExpects in unit test
   - minor code style changes


<?php

namespace CodeTool\ArtifactDownloader\UnitConfig;

use CodeTool\ArtifactDownloader\EtcdClient\EtcdClient;

class UnitConfig implements UnitConfigInterface
{
    private function getOptOrEnvOrDefault($optName, $env, $default)
    {
        $opt = getopt('', [$optName . '::']);
        if (false !== $opt && array_key_exists($optName, $opt)) {
            return $opt[$optName];
        }

        if (false !== ($envVal = getenv(sprintf('ENV_%s', $env)))) {
            return $envVal;
        }

        return $default;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->getOptOrEnvOrDefault('name', 'NAME', gethostname());
    }

    /**
     * @return string
     */
    public function getConfigPath()
    {
        return $this->getOptOrEnvOrDefault('config-path', 'CONFIG_PATH', 'artifact-downloader/config');
    }

    /**
     * @return string
     */
    public function getStatusDirectoryPath()
    {
        return $this->getOptOrEnvOrDefault('status-directory', 'STATUS_DIRECTORY', 'artifact-downloader/status');
    }

    /**
     * @return string
     */
    public function getResourceCredentialsConfigPath()
    {
        return $this->getOptOrEnvOrDefault('--resource-credentials', 'RESOURCE_CREDENTIALS', null);
    }

    /**
     * @return string
     */
    public function getEtcdServerUrl()
    {
        return $this->getOptOrEnvOrDefault('--etcd-server-url', 'ETCD_SERVER_URL', EtcdClient::DEFAULT_SERVER);
    }
}

<?php

namespace CodeTool\ArtifactDownloader\UnitConfig;

use CodeTool\ArtifactDownloader\EtcdClient\EtcdClient;

class UnitConfig implements UnitConfigInterface
{
    private function getOptOrEnvOrDefault($optName, $env, $default)
    {
        $opt = getopt('', [$optName . '::']);
        if (false !== $opt && array_key_exists($optName, $opt)) {
            return $opt[$optName];
        }

        if (false !== ($envVal = getenv(sprintf('ENV_%s', $env)))) {
            return $envVal;
        }

        return $default;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->getOptOrEnvOrDefault('name', 'NAME', gethostname());
    }

    /**
     * @return string
     */
    public function getConfigPath()
    {
        return $this->getOptOrEnvOrDefault('config-path', 'CONFIG_PATH', 'artifact-downloader/config');
    }

    /**
     * @return string
     */
    public function getStatusDirectoryPath()
    {
        return $this->getOptOrEnvOrDefault('status-directory', 'STATUS_DIRECTORY', 'artifact-downloader/status');
    }

    /**
     * @return string
     */
    public function getResourceCredentialsConfigPath()
    {
        return $this->getOptOrEnvOrDefault('resource-credentials', 'RESOURCE_CREDENTIALS', null);
    }

    /**
     * @return string
     */
    public function getEtcdServerUrl()
    {
        return $this->getOptOrEnvOrDefault('etcd-server-url', 'ETCD_SERVER_URL', EtcdClient::DEFAULT_SERVER);
    }
}

Fix some command line options parsing

Fix some command line options parsing


<?php

namespace spec;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class CaesarCipherSpec extends ObjectBehavior
{
    function it_converts_a_single_letter()
    {
        $this->encode(2, "a")->shouldReturn("c");
    }

    function it_converts_a_simple_string()
    {
        $this->encode(3, "abc")->shouldReturn("def");
    }

    function it_converts_a_more_complex_string()
    {
        $this->encode(3, "abc xyz")->shouldReturn("def abc");
    }

}

<?php

namespace spec;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class CaesarCipherSpec extends ObjectBehavior
{
    function it_converts_a_single_letter()
    {
        $this->encode(2, "a")->shouldReturn("c");
    }

    function it_converts_a_simple_string()
    {
        $this->encode(3, "abc")->shouldReturn("def");
    }

    function it_converts_a_complex_string()
    {
        $this->encode(5, "the quick brown fox jumps over the lazy dog")->shouldReturn("ymj vznhp gwtbs ktc ozrux tajw ymj qfed itl");
    }
}

Update caesar cipher complex example

Update caesar cipher complex example


<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.4';
}

<?php

require_once __DIR__ . '/Zigra/Core.php';
/**
 * This class only exists for backwards compatability. All code was moved to
 * Zigra_Core and this class extends Zigra_Core
 *
 * @author  Manuel Dalla Lana <endelwar@aregar.it>
 * @license Proprietary
 * @since   0.1.0
 */
class Zigra extends Zigra_Core
{
    const VERSION = '0.8.5';
}

Set release version to 0.8.5

Set release version to 0.8.5


<?php
namespace wcf\data\page;
use wcf\data\DatabaseObjectEditor;

/**
 * Provides functions to edit pages.
 *
 * @author	Marcel Werk
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	data.page
 * @category	Community Framework
 * @since	2.2
 */
class PageEditor extends DatabaseObjectEditor {
	/**
	 * @inheritDoc
	 */
	protected static $baseClass = Page::class;
}

<?php
namespace wcf\data\page;
use wcf\data\DatabaseObjectEditor;
use wcf\data\IEditableCachedObject;
use wcf\system\cache\builder\RoutingCacheBuilder;

/**
 * Provides functions to edit pages.
 *
 * @author	Marcel Werk
 * @copyright	2001-2015 WoltLab GmbH
 * @license	GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
 * @package	com.woltlab.wcf
 * @subpackage	data.page
 * @category	Community Framework
 * @since	2.2
 */
class PageEditor extends DatabaseObjectEditor implements IEditableCachedObject {
	/**
	 * @inheritDoc
	 */
	protected static $baseClass = Page::class;

	/**
	 * @inheritDoc
	 */
	public static function resetCache() {
		RoutingCacheBuilder::getInstance()->reset();
	}
}

Add missing cache reset after page changes


<?php

header('Content-Type: application/json');

//Variables
$user_agent = "lmgtfy/0.1 (https://github.com/shokinn/lmgtfy-slack-slash-command)";
$command = $_POST['command'];
$search = $_POST['text'];
$token = $_POST['token'];
$tokenMatch = "";

if($token != $tokenMatch){
    $msg = "The token for the slash command doesn't match. Check your script.";
    die($msg);
    echo $msg;
}

$longUrl = "http://lmgtfy.com/?q=".$search;

$reply_json = json_encode(array('response_type'=>'in_channel','text'=>"You'll find your answer here:\n*<".$longUrl.">.*"));
echo $reply_json;
?>

<?php

header('Content-Type: application/json');

//Variables
$user_agent = "lmgtfy/0.1 (https://github.com/shokinn/lmgtfy-slack-slash-command)";
$command = $_POST['command'];
$search = $_POST['text'];
$token = $_POST['token'];
$tokenMatch = "";

if($token != $tokenMatch){
    $msg = "{ \"error_msg\": \"The token for the slash command doesn't match. Check your script.\" }";
    die($msg);
    echo $msg;
}

$longUrl = "http://lmgtfy.com/?q=".$search;

$reply_json = json_encode(array('response_type'=>'in_channel','text'=>"You'll find your answer here:\n*<".$longUrl.">.*"));
echo $reply_json;
?>

Change error message from plain text to JSON.


	<footer>
		<div id="legal">
			<?php copyright('2011'); ?> <?php bloginfo('name'); ?>
		</div>
	</footer>

	<!--[if lt IE 7 ]>
	<script src="http://cdn.vanpattenmedia.com/js/libs/dd_belatedpng/0.0.8a/dd_belatedpng.js"></script>
	<script> DD_belatedPNG.fix('img, .png_fix');</script>
	<![endif]-->

<?php wp_footer(); ?>

<footer>
	<div id="legal">
		<?php copyright('2011'); ?> <?php bloginfo('name'); ?>
	</div>
</footer>

<?php wp_footer(); ?>

Remove png polyfill and some tabs

Remove png polyfill and some tabs


<?php

/**
 * Sample eecli Configuration file
 *
 * Rename this file to .eecli.php in your site root.
 */

return [
    /**
     * System path
     *
     * Specify the path to your EE system folder
     * If you leave this blank, it will assume your
     * folder is <current directory>/system
     */
    'system_path' => __DIR__.'/system',

    /**
     * Spoof $_SERVER variables
     *
     * This array will be merged with $_SERVER.
     *
     * When using php from the command line,
     * things like HTTP_HOST and DOCUMENT_ROOT
     * do not get set.
     *
     * Useful if you check for $_SERVER items
     * at runtime, like changing DB
     * credentials based on HTTP_HOST
     * in your config.php.
     */
    'server' => [
        'HTTP_HOST' => 'localhost',
        'DOCUMENT_ROOT' => __DIR__,
        'REQUEST_URI' => '/',
        'REMOTE_ADDR' => '127.0.0.1',
    ],

    /**
     * Assign variables to config
     */
    'assign_to_config' => [
        #'foo' => 'bar',
    ],

    /**
     * Custom commands
     *
     * An array of Command class names of
     * custom commands.
     */
    'commands' => [
        #'\\Your\\Custom\\Command',
    ],
];

<?php

/**
 * Sample eecli Configuration file
 *
 * Rename this file to .eecli.php in your site root.
 */

// Quit if this is not being requested via the CLI
if (php_sapi_name() !== 'cli') {
    exit;
}

return array(
    /**
     * System path
     *
     * Specify the path to your EE system folder
     * If you leave this blank, it will assume your
     * folder is <current directory>/system
     */
    'system_path' => __DIR__.'/system',

    /**
     * Spoof $_SERVER variables
     *
     * This array will be merged with $_SERVER.
     *
     * When using php from the command line,
     * things like HTTP_HOST and DOCUMENT_ROOT
     * do not get set.
     *
     * Useful if you check for $_SERVER items
     * at runtime, like changing DB
     * credentials based on HTTP_HOST
     * in your config.php.
     */
    'server' => array(
        'HTTP_HOST' => 'localhost',
        'DOCUMENT_ROOT' => __DIR__,
        'REQUEST_URI' => '/',
        'REMOTE_ADDR' => '127.0.0.1',
    ),

    /**
     * Assign variables to config
     */
    'assign_to_config' => array(
        #'foo' => 'bar',
    ),

    /**
     * Custom commands
     *
     * An array of Command class names of
     * custom commands.
     */
    'commands' => array(
        #'\\Your\\Custom\\Command',
    ),
);

Quit config file if not used from cli

Quit config file if not used from cli


@extends('layouts.master')

@section('main_content')

    @include('layouts.header', ['header' => 'Upload a CSV for import'])

                <form action={{url('/import')}} method="post" enctype="multipart/form-data">
                    {{ csrf_field()}}

                        Upload
                        <input type="file" name="upload-file" class="form-control">

                    Type of Import

                            <input checked type="checkbox" id="importType" value="turbovote" name="importType">

                            Turbovote Import

                        <input type="submit" class="button" value="Submit CSV">

                </form>

@stop

@extends('layouts.master')

@section('main_content')

    @include('layouts.header', ['header' => 'Upload a CSV for import'])

For the time being, This feature should only be used by Jen Ng. If you have any questions please reach out to Jen directly or post a message in the #rogue channel in slack

                <form action={{url('/import')}} method="post" enctype="multipart/form-data">
                    {{ csrf_field()}}

                        Upload
                        <input type="file" name="upload-file" class="form-control">

                    Type of Import

                            <input checked type="checkbox" id="importType" value="turbovote" name="importType">

                            Turbovote Import

                        <input type="submit" class="button" value="Submit CSV">

                </form>

@stop

Add a message that Jen is the only one to use this


<?php
// Сервер asset`ов

if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
} else {
    require_once __DIR__ . '/../../../autoload.php';
}

$projectDir   = getenv('projectDir');
$manifestPath = getenv('manifestPath');

$assetBuilder = new Dmitrynaum\SAM\AssetServerBuilder($manifestPath, $projectDir.'/');
$assetName    = isset($_GET['asset']) ? $_GET['asset'] : null;

try{
    $content = $assetBuilder->getAssetContentByName($assetName);
} catch (Exception $e) {
    if ($e->getCode() == 404) {
        header("HTTP/1.0 404 Not Found");
    } else {
        throw $e;
    }
}

echo $content;

<?php
// Сервер asset`ов

if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
} else {
    require_once __DIR__ . '/../../../autoload.php';
}

$projectDir   = getenv('projectDir');
$manifestPath = getenv('manifestPath');

$assetBuilder = new Dmitrynaum\SAM\AssetServerBuilder($manifestPath, $projectDir.'/');
$assetName    = isset($_GET['asset']) ? $_GET['asset'] : null;

try{
    $content = $assetBuilder->getAssetContentByName($assetName);
} catch (Exception $e) {
    if ($e->getCode() == 404) {
        header("HTTP/1.0 404 Not Found");
    } else {
        throw $e;
    }
}

$assetType   = pathinfo($assetName, PATHINFO_EXTENSION);
$contentType = '';
switch ($fileExtension) {
    case 'js':
        $contentType = 'application/javascript';
        break;
    case 'css':
        $contentType = 'text/css;charset=UTF-8';
        break;
}

header("Content-Type:{$contentType}");
echo $content;

Fix отправка заголовка встроенным сервером в зависимости от типа asset`а


<?php

require_once __DIR__."/../vendor/autoload.php";

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

function render_template($request)
{
    extract($request->attributes->all(), EXTR_SKIP);
    ob_start();
    include sprintf(__DIR__."/../src/pages/%s.php", $_route);

    return new Response(ob_get_clean(), 200);
}

$request = Request::createFromGlobals();
$routes = include __DIR__."/../src/app.php";

$context = new Routing\RequestContext();
$context->fromRequest($request);
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);

try{
    $request->attributes->add($matcher->match($request->getPathInfo()));
    $response = call_user_func($request->attributes->get('_controller'), $request);
}catch(Routing\Exception\ResourceNotFoundException $e) {
    $response = new Response('Not found', 404);
}catch(Exception $e){
    $response = new Response($e->getMessage(), 500);
}

$response->send();

<?php

require_once __DIR__."/../vendor/autoload.php";

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing;
use Symfony\Component\HttpKernel;
use Scarlett;

function render_template($request)
{
    extract($request->attributes->all(), EXTR_SKIP);
    ob_start();
    include sprintf(__DIR__."/../src/pages/%s.php", $_route);

    return new Response(ob_get_clean(), 200);
}

$request = Request::createFromGlobals();
$routes = include __DIR__."/../src/app.php";

$context = new Routing\RequestContext();
$context->fromRequest($request);
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);
$resolver = new HttpKernel\Controller\ControllerResolver();

$scarlett = new Scarlett\Framework($matcher, $resolver);
$response = $scarlett->handle($request);

$response->send();

Refactor code to use HttpKernel and a new Framework class


<?php

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

$app = require_once __DIR__ . '/../app/bootstrap.php';
$app->run();

<?php

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

use Asm89\Stack\Cors;
use Symfony\Component\HttpFoundation\Request;

$app = require_once __DIR__ . '/../app/bootstrap.php';

$stackedApp = new Cors($app, array(
    'allowedOrigins' => array('http://localhost:8000'),
    'allowedMethods' => array('DELETE', 'GET', 'PUT', 'POST'),
    'allowedHeaders' => array('accept', 'content-type', 'origin', 'x-requested-with'),
));

$request = Request::createFromGlobals();

$response = $stackedApp->handle($request);
$response->send();

$app->terminate($request, $response);

Add Cors to api. Configured for local development for now.


<?php

use GoogleLogin\AllowedDomains\ArrayAllowedDomainsStore;
use GoogleLogin\AllowedDomains\CachedAllowedDomainsStore;
use GoogleLogin\AllowedDomains\DBAllowedDomainsStore;
use GoogleLogin\Constants;
use GoogleLogin\GoogleIdProvider;
use GoogleLogin\GoogleLogin;
use GoogleLogin\GoogleUserMatching;
use MediaWiki\MediaWikiServices;

return [
	Constants::SERVICE_ALLOWED_DOMAINS_STORE => static function ( MediaWikiServices $services ) {
		$glConfig = GoogleLogin::getGLConfig();
		if (
			is_array( $glConfig->get( 'GLAllowedDomains' ) ) &&
			!$glConfig->get( 'GLAllowedDomainsDB' )
		) {
			return new ArrayAllowedDomainsStore( $glConfig->get( 'GLAllowedDomains' ) );
		} elseif ( $glConfig->get( 'GLAllowedDomainsDB' ) ) {
			$dbBackedStore = new DBAllowedDomainsStore( $services->getDBLoadBalancer() );
			$cache = wfGetCache( CACHE_ACCEL );

			return new CachedAllowedDomainsStore( $dbBackedStore, $cache );
		}
		return null;
	},

	Constants::SERVICE_GOOGLE_USER_MATCHING => static function ( MediaWikiServices $services ) {
		return new GoogleUserMatching( $services->getDBLoadBalancer() );
	},

	Constants::SERVICE_GOOGLE_ID_PROVIDER => static function ( MediaWikiServices $services ) {
		return new GoogleIdProvider( $services->getDBLoadBalancer() );
	}
];

<?php

use GoogleLogin\AllowedDomains\ArrayAllowedDomainsStore;
use GoogleLogin\AllowedDomains\CachedAllowedDomainsStore;
use GoogleLogin\AllowedDomains\DBAllowedDomainsStore;
use GoogleLogin\Constants;
use GoogleLogin\GoogleIdProvider;
use GoogleLogin\GoogleLogin;
use GoogleLogin\GoogleUserMatching;
use MediaWiki\MediaWikiServices;

return [
	Constants::SERVICE_ALLOWED_DOMAINS_STORE => static function ( MediaWikiServices $services ) {
		$glConfig = GoogleLogin::getGLConfig();
		if (
			is_array( $glConfig->get( 'GLAllowedDomains' ) ) &&
			!$glConfig->get( 'GLAllowedDomainsDB' )
		) {
			return new ArrayAllowedDomainsStore( $glConfig->get( 'GLAllowedDomains' ) );
		} elseif ( $glConfig->get( 'GLAllowedDomainsDB' ) ) {
			$dbBackedStore = new DBAllowedDomainsStore( $services->getDBLoadBalancer() );
			$cache = ObjectCache::getInstance( CACHE_ACCEL );

			return new CachedAllowedDomainsStore( $dbBackedStore, $cache );
		}
		return null;
	},

	Constants::SERVICE_GOOGLE_USER_MATCHING => static function ( MediaWikiServices $services ) {
		return new GoogleUserMatching( $services->getDBLoadBalancer() );
	},

	Constants::SERVICE_GOOGLE_ID_PROVIDER => static function ( MediaWikiServices $services ) {
		return new GoogleIdProvider( $services->getDBLoadBalancer() );
	}
];

Replace deprecated global function wfGetCache()

wfGetCache() is deprecated since 1.32

Bug: T293928
Change-Id: I61197c46e8d036ada703083c571504acb95f1ebb


<?php

			define('HOST', 'localhost');
			define('DB_USERNAME', 'my_username');
			define('DB_PASSWORD', 'my_password');
			define('DATABASE_NAME', 'my_database');

?>

<?php

			//Set database login parameters
			define('HOST', 'localhost');
			define('DB_USERNAME', 'my_username');
			define('DB_PASSWORD', 'my_password');
			define('DATABASE_NAME', 'my_database');

			//Set table & column names containing the required information (usernames, email addresses, passwords)
			define('TABLE_OF_USERS', 'my_table_name');
			define('COLUMN_OF_USERS', 'column_name');
			define('COLUMN_OF_EMAILS', 'column_name');
			define('COLUMN_OF_PASSWORDS', 'column_name');

?>

Add parameters defining table structure

Add parameters defining table structure


<?php namespace Northstar\Http\Controllers;

use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;

class AvatarController extends Controller
{

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

   /**
   * Store a new avatar for a user.
   * POST /users/{id}/avatar
   *
   * @param Request $request
   * @param $id - User ID
   * @return Response
   */
    public function store(Request $request, $id)
    {
        if ($request->file('photo')) {
            $file = $request->file('photo');
        } else {
            $file = $request->photo;
        }

        $this->validate($request, [
            'photo' => 'required'
        ]);

        $filename = $this->aws->storeImage('avatars', $id, $file);

        // Save filename to User model
        $user = User::where("_id", $id)->first();
        $user->photo = $filename;
        $user->save();

        // Respond to user with success and photo URL
        return $this->respond($user);
    }
}

<?php namespace Northstar\Http\Controllers;

use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;

class AvatarController extends Controller
{

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

    /**
     * Store a new avatar for a user.
     * POST /users/{id}/avatar
     *
     * @param Request $request
     * @param $id - User ID
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id)
    {
        if ($request->file('photo')) {
            $file = $request->file('photo');
        } else {
            $file = $request->photo;
        }

        $this->validate($request, [
            'photo' => 'required'
        ]);

        $filename = $this->aws->storeImage('avatars', $id, $file);

        // Save filename to User model
        $user = User::where("_id", $id)->first();
        $user->photo = $filename;
        $user->save();

        // Respond to user with success and photo URL
        return $this->respond($user);
    }
}

Fix indentation & class namespace.

Fix indentation & class namespace.


<?php
namespace jubianchi\PhpSwitch\PHP\Option;

use Symfony\Component\Console\Input\InputOption;
use jubianchi\PhpSwitch\Console\Command\Command;
use jubianchi\PhpSwitch\PHP\Option\Enable;

class AtoumOption extends Option
{
    const ARG = 'atoum';

    /**
     * @param \jubianchi\PhpSwitch\Console\Command\Command $command
     *
     * @return Option
     */
    public function applyArgument(Command $command)
    {
        if (static::ARG !== null && false === $command->getDefinition()->hasArgument(static::ARG)) {
            $command->addOption(
                static::ARG,
                null,
                InputOption::VALUE_NONE,
                sprintf('atoum compile options <comment>(%s)</comment>', $this)
            );
        }

        return $this;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return implode(
            ' ',
            array(
                new DisableAllOption(),
                new Enable\CLIOption(),
                new Enable\PHAROption(),
                new Enable\HashOption(),
                new Enable\JSONOption(),
                new Enable\XMLOption(),
                new Enable\SessionOption(),
                new Enable\TokenizerOption(),
                new Enable\PosixOption(),
                new Enable\DOMOption()
            )
        );
    }
}

<?php
namespace jubianchi\PhpSwitch\PHP\Option;

use Symfony\Component\Console\Input\InputOption;
use jubianchi\PhpSwitch\Console\Command\Command;
use jubianchi\PhpSwitch\PHP\Option\Enable;

class AtoumOption extends Option
{
    const ARG = 'atoum';

    /**
     * @param \jubianchi\PhpSwitch\Console\Command\Command $command
     *
     * @return Option
     */
    public function applyArgument(Command $command)
    {
        if (static::ARG !== null && false === $command->getDefinition()->hasArgument(static::ARG)) {
            $command->addOption(
                static::ARG,
                null,
                InputOption::VALUE_NONE,
                sprintf('atoum compile options <comment>(%s)</comment>', $this)
            );
        }

        return $this;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return implode(
            ' ',
            array(
                new DisableAllOption(),
                new Enable\CLIOption(),
                new Enable\PHAROption(),
                new Enable\HashOption(),
                new Enable\JSONOption(),
                new Enable\XMLOption(),
                new Enable\SessionOption(),
                new Enable\TokenizerOption(),
                new Enable\PosixOption(),
                new Enable\DOMOption(),
                new Enable\MBStringOption()
            )
        );
    }
}

Add mbstring option to atoum configuration


<?php

namespace Oro\Bundle\EntityBundle\Provider;

use Doctrine\ORM\QueryBuilder;

use Oro\Bundle\EntityBundle\ORM\SqlQueryBuilder;

interface DictionaryValueListProviderInterface
{
    /**
     * Gets a query builder for getting dictionary item values for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return QueryBuilder|SqlQueryBuilder|null QueryBuilder or SqlQueryBuilder if the provider can get values
     *                                           NULL if the provider cannot process the given entity
     */
    public function getValueListQueryBuilder($className);

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

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

<?php

namespace Oro\Bundle\EntityBundle\Provider;

use Doctrine\ORM\QueryBuilder;

use Oro\Bundle\EntityBundle\ORM\SqlQueryBuilder;

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

    /**
     * Gets a query builder for getting dictionary item values for a given dictionary class
     *
     * @param string $className The FQCN of a dictionary entity
     *
     * @return QueryBuilder|SqlQueryBuilder|null QueryBuilder or SqlQueryBuilder if the provider can get values
     *                                           NULL if the provider cannot process the given entity
     */
    public function getValueListQueryBuilder($className);

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

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

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


<?php
/**
 * @version     $Id$
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Newsfeeds Toolbar Class
 *
 * @author      Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */
class ComNewsfeedsControllerToolbarNewsfeeds extends ComDefaultControllerToolbarDefault
{
    public function __construct(KConfig $config)
    {
        parent::__construct($config);

        $this->addSeperator()
			 ->addEnable()
			 ->addDisable();
    }
}

<?php
/**
 * @version     $Id$
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Newsfeeds Toolbar Class
 *
 * @author      Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */
class ComNewsfeedsControllerToolbarNewsfeeds extends ComDefaultControllerToolbarDefault
{
    public function getCommands()
    {
        $this->addSeperator()
			 ->addEnable()
			 ->addDisable();

	    return parent::getCommands();
    }
}

Insert custom commands through the getCommands() function.


<?php

namespace Framework;

class Controller {

	private $app;
	private $api;

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

	protected function setHeader($header, $value)
	{
		$this->app->response->headers->set($header, $value);
	}

	protected function setLayout($layout) {
		$this->app->view->setLayout($layout);
	}

	protected function render($name, $data=array()) {
		return $this->app->render($name, $data);
	}

	protected function redirect($url, $params=null) {
		if ($params !== null) $url = $this->app->urlFor($url, $params);
		return $this->app->redirect($url);
	}

	protected function params($name = null) {
		return $this->app->request->params($name);
	}

	protected function urlFor($name, $params=array()) {
		return $this->app->router->urlFor($name, $params);
	}

	protected function current_user() {
		return $this->app->current_user;
	}

	protected function api() {
		if (!isset($this->api)) {
			$this->api = new \App\Lib\Api($_COOKIE['Token']);
		}
		return $this->api;
	}

}

<?php

namespace Framework;

class Controller {

	private $app;
	private $api;

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

	protected function setHeader($header, $value)
	{
		$this->app->response->headers->set($header, $value);
	}

	protected function setLayout($layout) {
		$this->app->view->setLayout($layout);
	}

	protected function render($name, $data=array()) {
		return $this->app->render($name, $data);
	}

	protected function flash($key, $value)
	{
		$this->app->flash($key, $value);
	}

	protected function redirect($url, $params=null) {
		if ($params !== null) $url = $this->app->urlFor($url, $params);
		return $this->app->redirect($url);
	}

	protected function params($name = null) {
		return $this->app->request->params($name);
	}

	protected function urlFor($name, $params=array()) {
		return $this->app->router->urlFor($name, $params);
	}

	protected function current_user() {
		return $this->app->current_user;
	}

	protected function api() {
		if (!isset($this->api)) {
			$this->api = new \App\Lib\Api($_COOKIE['Token']);
		}
		return $this->api;
	}

}

Add support for flash messages

Add support for flash messages


<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Diskreport extends Migration
{
    public function up()
    {
        $capsule = new Capsule();

        $legacy_migration_version = $capsule::table('migration')
            ->where('table_name', '=', 'diskreport')
            ->first(['version']);

        if ($legacy_migration_version && $legacy_migration_version->version === 3) {
            // No need to run this migration
        } else {
            $capsule::schema()->create('diskreport', function (Blueprint $table) {
                $table->increments('id');

                $table->string('serial_number');
                $table->bigInteger('TotalSize');
                $table->bigInteger('FreeSpace');
                $table->bigInteger('Percentage');
                $table->string('SMARTStatus');
                $table->string('VolumeType');
                $table->string('media_type');
                $table->string('BusProtocol');
                $table->integer('Internal');
                $table->string('MountPoint');
                $table->string('VolumeName');
                $table->integer('CoreStorageEncrypted');
                $table->string('timestamp');

                $table->index('serial_number', 'diskreport_serial_number');
                $table->index('MountPoint', 'diskreport_MountPoint');
                $table->index('media_type', 'diskreport_media_type');
                $table->index('VolumeName', 'diskreport_VolumeName');
                $table->index('VolumeType', 'diskreport_VolumeType');

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

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('diskreport');
    }
}

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Diskreport extends Migration
{
    public function up()
    {
        $capsule = new Capsule();

        $capsule::schema()->create('diskreport', function (Blueprint $table) {
            $table->increments('id');

            $table->string('serial_number');
            $table->bigInteger('TotalSize');
            $table->bigInteger('FreeSpace');
            $table->bigInteger('Percentage');
            $table->string('SMARTStatus');
            $table->string('VolumeType');
            $table->string('media_type');
            $table->string('BusProtocol');
            $table->integer('Internal');
            $table->string('MountPoint');
            $table->string('VolumeName');
            $table->integer('CoreStorageEncrypted');
            $table->string('timestamp');

            $table->index('serial_number', 'diskreport_serial_number');
            $table->index('MountPoint', 'diskreport_MountPoint');
            $table->index('media_type', 'diskreport_media_type');
            $table->index('VolumeName', 'diskreport_VolumeName');
            $table->index('VolumeType', 'diskreport_VolumeType');

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

    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('diskreport');
    }
}

Remove legacy check from diskreport migration