<?php

use pendalf89\filemanager\Module;
use pendalf89\filemanager\assets\ModalAsset;
use yii\helpers\Url;

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

$this->title = Module::t('main', 'Files');
$this->params['breadcrumbs'][] = ['label' => Module::t('main', 'File manager'), 'url' => ['default/index']];
$this->params['breadcrumbs'][] = $this->title;

ModalAsset::register($this);
?>

<iframe src="<?= Url::to(['/filemanager/file/filemanager']) ?>" id="post-original_thumbnail-frame" frameborder="0" role="filemanager-frame"></iframe>

<?php

use pendalf89\filemanager\Module;
use pendalf89\filemanager\assets\ModalAsset;
use yii\helpers\Url;

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

$this->title = Module::t('main', 'Files');
$this->params['breadcrumbs'][] = ['label' => Module::t('main', 'File manager'), 'url' => ['default/index']];
$this->params['breadcrumbs'][] = $this->title;

ModalAsset::register($this);
?>

<iframe src="<?= Url::to(['file/filemanager']) ?>" id="post-original_thumbnail-frame" frameborder="0" role="filemanager-frame"></iframe>

Revert "The url for the modal file window was corrected"

This reverts commit 4d357db0a731837900a88dfdb4535f0268885a9e.


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
}

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
}

Fix RedirectUrl for Password Resets

Fix RedirectUrl for Password Resets


<?php
namespace ShinyGeoip\Responder;

use ShinyGeoip\Core\Responder;

class ApiRequestResponder extends Responder
{
    /**
     * Echos short version of record as json encodes string.
     */
    public function short()
    {
        $this->setContentTypeHeader('json');
        $record = $this->get('record');
        echo json_encode($record);
    }

    /**
     * Echos the full record as json encoded string.
     */
    public function full()
    {
        $this->setContentTypeHeader('json');
        $record = $this->get('record')->jsonSerialize();
        echo json_encode($record);
    }

    /**
     * Echos a json encoded not found error message.
     */
    public function notFound()
    {
        $this->setContentTypeHeader('json');
        echo json_encode(['type' => 'error', 'msg' => 'No record found.']);
    }
}

<?php
namespace ShinyGeoip\Responder;

use ShinyGeoip\Core\Responder;

class ApiRequestResponder extends Responder
{
    /**
     * Echos short version of record as json encodes string.
     */
    public function short()
    {
        $this->setContentTypeHeader('json');
        $record = $this->get('record');
        echo json_encode($record);
        exit;
    }

    /**
     * Echos the full record as json encoded string.
     */
    public function full()
    {
        $this->setContentTypeHeader('json');
        $record = $this->get('record')->jsonSerialize();
        echo json_encode($record);
        exit;
    }

    /**
     * Echos a json encoded not found error message.
     */
    public function notFound()
    {
        $this->setContentTypeHeader('json');
        echo json_encode(['type' => 'error', 'msg' => 'No record found.']);
        exit;
    }
}

Stop script execution after output of json-data so content type header is correct.


<?php

/**
 * @author    Andreas Fischer <bantu@phpbb.com>
 * @copyright MMXIV Andreas Fischer
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
 */

class Net_SSH2FunctionalTest extends PhpseclibFunctionalTestCase
{
    public function testConstructor()
    {
        $ssh = new Net_SSH2($this->getEnv('SSH_HOSTNAME'));

        $this->assertTrue(
            is_object($ssh),
            'Could not construct NET_SSH2 object.'
        );

        return $ssh;
    }

    /**
    * @depends testConstructor
    */
    public function testPasswordLogin($ssh)
    {
        $username = $this->getEnv('SSH_USERNAME');
        $password = $this->getEnv('SSH_PASSWORD');
        $this->assertTrue(
            $ssh->login($username, $password),
            'SSH2 login using password failed.'
        );
    }
}

<?php

/**
 * @author    Andreas Fischer <bantu@phpbb.com>
 * @copyright MMXIV Andreas Fischer
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
 */

class Net_SSH2FunctionalTest extends PhpseclibFunctionalTestCase
{
    public function setUp()
    {
        if (getenv('TRAVIS') && version_compare(PHP_VERSION, '5.3.3', '<=')) {
            $this->markTestIncomplete(
                'This test hangs on Travis CI on PHP 5.3.3 and below.'
            );
        }
        parent::setUp();
    }

    public function testConstructor()
    {
        $ssh = new Net_SSH2($this->getEnv('SSH_HOSTNAME'));

        $this->assertTrue(
            is_object($ssh),
            'Could not construct NET_SSH2 object.'
        );

        return $ssh;
    }

    /**
    * @depends testConstructor
    */
    public function testPasswordLogin($ssh)
    {
        $username = $this->getEnv('SSH_USERNAME');
        $password = $this->getEnv('SSH_PASSWORD');
        $this->assertTrue(
            $ssh->login($username, $password),
            'SSH2 login using password failed.'
        );
    }
}

Mark SSH2 Test as Incomplete on Travis PHP 5.3.3 and below for now.


<?php

namespace j0k3r\FeedBundle\Parser;

/**
 * HackernewsParser
 *
 * This class provides a custom parser for news.ycombinator.com feed
 */
class HackernewsParser extends DefaultParser
{
    /**
     * We just append the readable content to the default content.
     * In fact, we transform the "Comments" link, to something a bit more friendly
     */
    public function updateContent($content)
    {
        $url_parts = parse_url($this->url);

        return '
Original article on url.'">'.$url_parts['host'].'
 '.$content;
    }
}

<?php

namespace j0k3r\FeedBundle\Parser;

/**
 * HackernewsParser
 *
 * This class provides a custom parser for news.ycombinator.com feed
 */
class HackernewsParser extends DefaultParser
{
    /**
     * We append the readable content to something a bit more friendly:
     * - a link to the original article with the host as value
     * - a link to comments on Hacker News
     */
    public function updateContent($content)
    {
        $url_parts = parse_url($this->url);

        // $itemContent for HackerNews feed contains only a link to the HN page with "Comments" as name
        return '
Original article on url.'">'.$url_parts['host'].' - '.$this->itemContent.' on Hacker News
 '.$content;
    }
}

Add comments link to the HN thread

Add comments link to the HN thread


<?php

/**
 * Class GalleryImageExtension
 *
 * @property Image|GalleryImageExtension $owner
 */
class GalleryImageExtension extends DataExtension
{

	private static $db = array(
		'Caption'	=> 'Text',
	);

	private static $belongs_many_many = array(
		'GalleryPage'	=> 'GalleryPage',
	);

	public function updateCMSFields(FieldList $fields)
	{
		$fields->addFieldToTab('Root.Main', new TextField('Caption', 'Kuvateksti'), 'Title');
		$fields->removeFieldsFromTab('Root.Main', array('Title','Name','OwnerID','ParentID'));
	}

	public function GalleryThumbnail()
	{
		return $this->owner->Fit($this->GalleryThumbnailWidth(), $this->GalleryThumbnailHeight());
	}

	public function GalleryThumbnailWidth()
	{
		return (int) GalleryImage::config()->get('thumbnail_width');
	}

	public function GalleryThumbnailHeight()
	{
		return (int) GalleryImage::config()->get('thumbnail_height');
	}

}

<?php

/**
 * Class GalleryImageExtension
 *
 * @property Image|GalleryImageExtension $owner
 */
class GalleryImageExtension extends DataExtension
{

	private static $db = array(
		'Caption'	=> 'Text',
	);

	private static $belongs_many_many = array(
		'GalleryPage'	=> 'GalleryPage',
	);

	public function updateCMSFields(FieldList $fields)
	{
		$fields->addFieldToTab('Root.Main', new TextField('Caption', 'Kuvateksti'), 'Title');
		$fields->removeFieldsFromTab('Root.Main', array('Title','Name','OwnerID','ParentID'));
	}

	public function GalleryThumbnail()
	{
		return $this->owner->Fit($this->GalleryThumbnailWidth(), $this->GalleryThumbnailHeight());
	}

	public function GalleryThumbnailWidth()
	{
		return (int) GalleryImage::config()->get('thumbnail_width');
	}

	public function GalleryThumbnailHeight()
	{
		return (int) GalleryImage::config()->get('thumbnail_height');
	}

	public function BootstrapCSSColumnClasses()
	{
		$columns = GalleryImage::config()->get('thumbnail_cols');
		$result = '';
		foreach ($columns as $type => $size)
		{
			if ($result) $result .= ' ';
			$result .= "col-$type-$size"; //For example: col-md-12
		}
		return $result;
	}

}

Create a method that generates a concatenated list of Bootstrap CSS col-*-* classes suitable for thumbnails.


<?php

namespace fennecweb\ajax\details;

class ProjectsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'detailsProjectsTestUser';
    const USERID = 'detailsProjectsTestUser';
    const PROVIDER = 'detailsProjectsTestUser';

    public function testExecute()
    {
        //Test if the selected project contains the correct information
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'detailsProjectTestUserToken'
        );
        list($service) = WebService::factory('details/Project');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
        $expected = array(
                      'table_1'
        );
        $this->assertArraySubset($expected, $results);
    }
}

<?php

namespace fennecweb\ajax\details;

class ProjectsTest extends \PHPUnit_Framework_TestCase
{
    const NICKNAME = 'detailsProjectsTestUser';
    const USERID = 'detailsProjectsTestUser';
    const PROVIDER = 'detailsProjectsTestUser';

    public function testExecute()
    {
        //Test if the selected project contains the correct information
        $_SESSION['user'] = array(
            'nickname' => ProjectsTest::NICKNAME,
            'id' => ProjectsTest::USERID,
            'provider' => ProjectsTest::PROVIDER,
            'token' => 'detailsProjectTestUserToken'
        );
        list($service) = \fennecweb\WebService::factory('details/Projects');
        $results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'id' => 'table_1')));
        $expected = array(
                      'table_1'
        );
        $this->assertArraySubset($expected, $results);
    }
}

Add correct namespace to webservice and add project id to querydata


<?php

namespace spec\SearchApi\Providers;

use SearchApi;
use SearchApi\Models;
use SearchApi\Services\Search;
use SearchApi\Builders\QueryBuilder;
use SearchApi\Clients\HttpClient;

use PhpSpec\ObjectBehavior;

/**
 * SolrSearchSpec - Spec test for SolrSearch
 */
class SolrSearchSpec extends ObjectBehavior {
  function it_is_initializable() {
    $this->shouldHaveType( 'SearchApi\Providers\SolrSearch' );
  }

  function it_should_call_query_builder( QueryBuilder $queryBuilder ) {
    $this->beConstructedWith( $queryBuilder );

    $queryBuilder->build( 'test', null )->shouldBeCalled();

    $this->query( 'test' );
  }

  function it_should_return_null_when_keywords_empty() {
    $result = $this->query( null );

    $result->shouldBeNull();
  }

  function it_should_return_search_result_when_keywords_not_empty( QueryBuilder $queryBuilder, HttpClient $httpClient ) {
    $queryBuilder->build( 'test', null )->willReturn( 'test_query' );
    $httpClient->get( 'test_query' )->willReturn( '{"responseHeader":{"response":{"numFound":1,"start":0,"docs":[{"id":"testid","author":"testauthor","date":"testdate","content":"testcontent"}]}}' );

    $result = $this->query( 'test' );
    $result->shouldHaveType( 'SearchApi\Models\SearchResult' );
    $result->count->shouldBe( 1 );
  }
}

<?php

namespace spec\SearchApi\Providers;

use SearchApi;
use SearchApi\Models;
use SearchApi\Services\Search;
use SearchApi\Builders\QueryBuilder;
use SearchApi\Clients\HttpClient;

use PhpSpec\ObjectBehavior;

/**
 * SolrSearchSpec - Spec test for SolrSearch
 */
class SolrSearchSpec extends ObjectBehavior {
  function it_is_initializable() {
    $this->shouldHaveType( 'SearchApi\Providers\SolrSearch' );
  }

  function it_should_call_query_builder( QueryBuilder $queryBuilder ) {
    $this->beConstructedWith( $queryBuilder );

    $queryBuilder->build( 'test', null )->shouldBeCalled();

    $this->query( 'test' );
  }

  function it_should_return_null_when_keywords_empty() {
    $result = $this->query( null );

    $result->shouldBeNull();
  }

  function it_should_return_search_result_when_keywords_not_empty( QueryBuilder $queryBuilder, HttpClient $httpClient ) {
    $queryBuilder->build( 'test', null )->willReturn( 'test_query' );
    $httpClient->get( 'test_query' )->willReturn( '{"response":{"numFound":1,"start":0,"docs":[{"id":"testid","author":"testauthor","date":"testdate","content":"testcontent"}]}}' );

    $result = $this->query( 'test' );
    $result->shouldHaveType( 'SearchApi\Models\SearchResult' );
    $result->count->shouldBe( 1 );
  }
}

Fix typo in json string

Fix typo in json string


<?php
/*
 * Basic page
 */
?>

<?php echo _('Heading')?>

		<?php echo _('Page info')?>

						Page contents

					Item One (active!)
					Item two

Fix the divs, do away with the 4/8 format


<?php

namespace Lstr\Sprintf;

class Sprintf
{
    /**
     * @var callable
     */
    private $middleware;

    /**
     * @var Processor
     */
    private $processor;

    /**
     * @param callable $middleware
     * @param Processor $processor
     */
    public function __construct(callable $middleware = null, Processor $processor = null)
    {
        $this->middleware = $middleware;
        $this->processor = $processor;
    }

    /**
     * @param string $format
     * @param array $parameters
     * @return string
     */
    public function sprintf($format, array $parameters)
    {
        $parsed_expression = $this->getProcessor()->parse($format, $parameters);

        return $parsed_expression->format($parameters, $this->middleware);
    }

    /**
     * @return Processor
     */
    private function getProcessor()
    {
        if ($this->processor) {
            return $this->processor;
        }

        $this->processor = new Processor($this->middleware);

        return $this->processor;
    }
}

<?php

namespace Lstr\Sprintf;

class Sprintf
{
    /**
     * @var callable
     */
    private $middleware;

    /**
     * @var Processor
     */
    private $processor;

    /**
     * @param callable $middleware
     * @param Processor $processor
     */
    public function __construct(callable $middleware = null, Processor $processor = null)
    {
        $this->middleware = $middleware;
        $this->processor = $processor;
    }

    /**
     * @param string $format
     * @param array $parameters
     * @return string
     */
    public function sprintf($format, array $parameters)
    {
        $parsed_expression = $this->getProcessor()->parse($format, $parameters);

        return $parsed_expression->format($parameters, $this->middleware);
    }

    /**
     * @return Processor
     */
    private function getProcessor()
    {
        if ($this->processor) {
            return $this->processor;
        }

        $this->processor = new Processor();

        return $this->processor;
    }
}

Stop passing middleware to Processor constructor

The middleware is no longer used by the processor.


<?php

if ( ! function_exists('fs_asset')) {
    function fs_asset($assetFolder, $afterPath, $force = false)
    {
        return \Reshadman\FileSecretary\Infrastructure\UrlGenerator::asset($assetFolder, $afterPath, $force);
    }
}

Add helper function for asset

Add helper function for asset


<?php
	session_start();
?>
<!DOCTYPE html>

		<meta charset="utf-8" />

		<title>SSBO Ticketing - Login</title>
		<meta name="description" content="SSBO Ticketing System Login" />
		<meta name="author" content="Marius Runde" />

		<link rel="stylesheet" href="style.css" />

		<link rel="shortcut icon" href="img/favicon.png" />

SSBO Ticketing - Login

		<form name="control_form" action="index.php" method="post">
			<input name="user" type="text" value="" placeholder="Nutzername eingeben..." />

			<input name="pass" type="password" value="" placeholder="Passwort eingeben..." />

			<button type="submit">Anmelden</button>
		</form>

				© Copyright 2014 by Marius Runde

<?php
	session_start();
?>
<!DOCTYPE html>

		<meta charset="utf-8" />

		<title>SSBO Ticketing - Login</title>
		<meta name="description" content="SSBO Ticketing System Login" />
		<meta name="author" content="Marius Runde" />

		<link rel="stylesheet" href="style.css" />

		<link rel="shortcut icon" href="img/favicon.png" />

SSBO Ticketing - Login

		<form name="control_form" action="index.php" method="post">
			<input name="user" type="text" value="" placeholder="Nutzername eingeben..." autofocus />

			<input name="pass" type="password" value="" placeholder="Passwort eingeben..." />

			<button type="submit">Anmelden</button>
		</form>

				© Copyright 2014 by Marius Runde

Add autofocus to login form

Add autofocus to login form


<?php

class MigrationRunnerTest extends PHPUnit_Framework_TestCase
{
    function testRunner()
    {
        LazyRecord\QueryDriver::free();
        $connm = LazyRecord\ConnectionManager::getInstance();
        $connm->addDataSource('default',array( 'dsn' => 'sqlite::memory:' ));

        $runner = new LazyRecord\Migration\MigrationRunner('default');
        ok($runner);

        $runner->load('tests/migrations');
        return $runner;
    }

    /**
     * @depends testRunner
     */
    function testUpgrade($runner)
    {
        $this->expectOutputRegex('#CreateUser_1346436136#');
        $this->expectOutputRegex('#QueryOK#');
        $runner->runUpgrade();
        return $runner;
    }

    /**
     * @depends testUpgrade
     */
    function testDowngrade($runner)
    {
        $this->expectOutputRegex('#Running downgrade migration script#');
        $runner->runDowngrade();
    }
}

<?php

class MigrationRunnerTest extends PHPUnit_Framework_TestCase
{
    function testRunner()
    {
        $connm = LazyRecord\ConnectionManager::getInstance();
        $connm->addDataSource('default',array( 'dsn' => 'sqlite::memory:' ));

        $runner = new LazyRecord\Migration\MigrationRunner('default');
        ok($runner);

        $runner->load('tests/migrations');
        return $runner;
    }

    /**
     * @depends testRunner
     */
    function testUpgrade($runner)
    {
        $this->expectOutputRegex('#CreateUser_1346436136#');
        $this->expectOutputRegex('#QueryOK#');
        $runner->runUpgrade();
        return $runner;
    }

    /**
     * @depends testUpgrade
     */
    function testDowngrade($runner)
    {
        $this->expectOutputRegex('#Running downgrade migration script#');
        $runner->runDowngrade();
    }
}

Fix join condition and remove QueryDriver::free statement


<?php

namespace Trappar\AliceGenerator\Metadata\Resolver\Faker;

use Trappar\AliceGenerator\DataStorage\ValueContext;
use Trappar\AliceGenerator\Faker\FakerGenerator;
use Trappar\AliceGenerator\Metadata\Resolver\AbstractMetadataResolver;

abstract class AbstractFakerResolver extends AbstractMetadataResolver implements FakerResolverInterface
{
    public function resolve(ValueContext $valueContext)
    {
        $this->validate($valueContext);

        $result = $this->handle($valueContext);

        if (!$result instanceof ValueContext) {
            if (is_array($result)) {
                $result = FakerGenerator::generate($valueContext->getMetadata()->fakerName, $result);
            }
            $valueContext->setValue($result);
        }
    }

    /**
     * @inheritDoc
     */
    public function validate(ValueContext $valueContext)
    {
    }
}

<?php

namespace Trappar\AliceGenerator\Metadata\Resolver\Faker;

use Trappar\AliceGenerator\DataStorage\ValueContext;
use Trappar\AliceGenerator\Faker\FakerGenerator;
use Trappar\AliceGenerator\Metadata\Resolver\AbstractMetadataResolver;

abstract class AbstractFakerResolver extends AbstractMetadataResolver implements FakerResolverInterface
{
    final public function resolve(ValueContext $valueContext)
    {
        $this->validate($valueContext);

        $result = $this->handle($valueContext);

        if (!$result instanceof ValueContext) {
            if (is_array($result)) {
                $result = FakerGenerator::generate($valueContext->getMetadata()->fakerName, $result);
            }
            $valueContext->setValue($result);
        }
    }

    /**
     * @inheritDoc
     */
    public function validate(ValueContext $valueContext)
    {
    }
}

Make abstract method final to avoid unwanted overloading


<?php

namespace Drupal\AppConsole\Command\Helper;

use Symfony\Component\Console\Helper\DialogHelper as BaseDialogHelper;
use Symfony\Component\Console\Output\OutputInterface;

class DialogHelper extends BaseDialogHelper
{
    public function writeGeneratorSummary(OutputInterface $output, $errors)
    {
        if (!$errors) {
            $this->writeSection($output, 'You can now start using the generated code!');
        } else {
            $this->writeSection($output, array(
                'The command was not able to configure everything automatically.',
                'You must do the following changes manually.',
            ), 'error');

            $output->writeln($errors);
        }
    }

    public function getRunner(OutputInterface $output, &$errors)
    {
        $runner = function ($err) use ($output, &$errors) {
            if ($err) {
                $output->writeln('<fg=red>FAILED</>');
                $errors = array_merge($errors, $err);
            } else {
                $output->writeln('<info>OK</info>');
            }
        };

        return $runner;
    }

    public function writeSection(OutputInterface $output, $text, $style = 'bg=blue;fg=white')
    {
        $output->writeln(array(
            '',
            $this->getHelperSet()->get('formatter')->formatBlock($text, $style, true),
            '',
        ));
    }

    public function getQuestion($question, $default, $sep = ':')
    {
        return $default ? sprintf('<info>%s</info> [<comment>%s</comment>]%s ', $question, $default, $sep) : sprintf('<info>%s</info>%s ', $question, $sep);
    }
}

<?php

namespace Drupal\AppConsole\Command\Helper;

use Symfony\Component\Console\Helper\DialogHelper as BaseDialogHelper;
use Symfony\Component\Console\Output\OutputInterface;

class DialogHelper extends BaseDialogHelper
{

    public function writeSection(OutputInterface $output, $text, $style = 'bg=blue;fg=white')
    {
        $output->writeln(array(
            '',
            $this->getHelperSet()->get('formatter')->formatBlock($text, $style, true),
            '',
        ));
    }

    public function getQuestion($question, $default, $sep = ':')
    {
        return $default ? sprintf('<info>%s</info> [<comment>%s</comment>]%s ', $question, $default, $sep) : sprintf('<info>%s</info>%s ', $question, $sep);
    }
}

Remove no longer needed methods

Remove no longer needed methods


<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Note;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

class NoteController extends Controller
{
    /**
     * @Route("/note")
     */
    public function indexAction()
    {
      $notes = $this->getDoctrine()
            ->getRepository('AppBundle:Note')
            ->findAll();

        return $this->render(
            'note/index.html.twig',
            array('notes' => $notes)
        );
    }

    /**
     * @Route("/note/{id}")
     * @ParamConverter("note", class="AppBundle:Note")
    */
    public function showAction(Note $note)
    {
    }

    /**
     * @Route("/note/create")
    */
    public function createAction()
    {
      $note = new Note();
      $note->setContent('My very first note');

      $em = $this->getDoctrine()->getManager();

      $em->persist($note);
      $em->flush();

      return new Response('Created note id '.$note->getId());
    }
}

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Note;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;

class NoteController extends Controller
{
    /**
     * @Route("/note")
     */
    public function indexAction()
    {
      $notes = $this->getDoctrine()
            ->getRepository('AppBundle:Note')
            ->findAll();

        return $this->render(
            'note/index.html.twig',
            array('notes' => $notes)
        );
    }

    /**
     * @Route("/note/create")
     */
    public function createAction()
    {
      $note = new Note();
      $note->setContent('My very first note');
      $note->setIsPublic(true);

      $em = $this->getDoctrine()->getManager();

      $em->persist($note);
      $em->flush();

      return new Response('Created note id '.$note->getId());
    }
}

Set is_public on create note

Set is_public on create note


<?php

namespace ChopBox\Http\Controllers;

use Illuminate\Http\Request;

use ChopBox\Http\Requests;
use ChopBox\Http\Controllers\Controller;

class HelpAndPrivacyController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function help()
    {
        return view('pages.help');
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function privacy()
    {
        return view('pages.privacy');
    }
}

<?php

namespace ChopBox\Http\Controllers;

use ChopBox\Http\Requests;
use Illuminate\Http\Request;
use ChopBox\Http\Controllers\Controller;

class HelpAndPrivacyController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function help()
    {
        return view('pages.help');
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function privacy()
    {
        return view('pages.privacy');
    }
}

[Chopbox] Arrange imports from shortest to longest


<?php namespace Watson\Active;

use Illuminate\Support\ServiceProvider;

class ActiveServiceProvider extends ServiceProvider {

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

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

		$this->app->bind('active', function()
		{
			return new \Watson\Active\Active($app['request'], $app['router']);
		});
	}

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

}

<?php namespace Watson\Active;

use Illuminate\Support\ServiceProvider;

class ActiveServiceProvider extends ServiceProvider {

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

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->bind('active', function()
		{
			return new \Watson\Active\Active($app['request'], $app['router']);
		});
	}

	/**
	 * Boot the service provider.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('watson/active');
	}

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

}

Move the package registration to the service provider boot() method


<?php
namespace common\models;

use common\helpers\Utils;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class EventLog extends EventLogBase
{
    /**
     * @return array
     */
    public function rules()
    {
        return ArrayHelper::merge(
            [

                [
                    ['created'], 'default', 'value' => Utils::getDatetime(),
                ],

            ],
            parent::rules()
        );
    }

    /**
     * Create new EventLog entry
     * @param string $topic
     * @param string|array $details
     * @param integer|null $userId
     * @throws \Exception
     */
    public static function log($topic, $details, $userId = null)
    {
        $eventLog = new EventLog();
        $eventLog->user_id = $userId;
        $eventLog->topic = $topic;
        $eventLog->details = is_array($details) ? Json::encode($details) : $details;

        /*
         * Save event to LogEntries
         */
        try {
            $user = User::findOne(['id' => $userId]);
            if ($user !== null) {
                \Yii::warning([
                   'action' => 'eventlog',
                    'user' => $user->email,
                    'topic' => $topic,
                    'details' => $details,
                ]);
            }
        } catch (\Exception $ex) {

        }

        if ( ! $eventLog->save()) {
            throw new \Exception('Unable to save event log entry', 1461182172);
        }
    }

}

<?php
namespace common\models;

use common\helpers\Utils;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class EventLog extends EventLogBase
{
    /**
     * @return array
     */
    public function rules()
    {
        return ArrayHelper::merge(
            [

                [
                    ['created'], 'default', 'value' => Utils::getDatetime(),
                ],

            ],
            parent::rules()
        );
    }

    /**
     * Create new EventLog entry
     * @param string $topic
     * @param string|array $details
     * @param integer|null $userId
     * @throws \Exception
     */
    public static function log($topic, $details, $userId = null)
    {
        $eventLog = new EventLog();
        $eventLog->user_id = $userId;
        $eventLog->topic = $topic;
        $eventLog->details = is_array($details) ? Json::encode($details) : $details;

        /*
         * Save event to LogEntries
         */
        try {
            $user = User::findOne(['id' => $userId]);
            if ($user !== null) {
                \Yii::warning([
                   'action' => 'eventlog',
                    'user' => $user->email,
                    'topic' => $topic,
                    'details' => $details,
                ]);
            }
        } catch (\Exception $ex) {
            /*
             * ignore exception to continue execution in this function
             */
        }

        if ( ! $eventLog->save()) {
            throw new \Exception('Unable to save event log entry', 1461182172);
        }
    }

}

Address Scrutinizer issue on empty catch block.


<!DOCTYPE html>

	<?php include("../include/common.html"); ?>
	<link rel="stylesheet" type="text/css" href="../styles/host.css">
	<meta name="apple-mobile-web-app-title" content="GAMR - Host A Game">
	<meta name="og:title" content="GAMR - Host A Game">
	<title>Host A Game</title>

	<?php include("../include/header.php"); ?>

Thank you for hosting a game!

We just need a little bit of information from you to set this up.

		<form id="new-game">
			<input type="text" placeholder="Which game are you playing?">
			<input type="number" placeholder="How many people do you want?">
			<input type="submit" value="Host this game">
		</form>
	<?php include("../include/footer.html"); ?>

<!DOCTYPE html>

	<?php include("../include/common.html"); ?>
	<link rel="stylesheet" type="text/css" href="../styles/host.css">
	<meta name="apple-mobile-web-app-title" content="GAMR - Host A Game">
	<meta name="og:title" content="GAMR - Host A Game">
	<title>Host A Game</title>

	<?php include("../include/header.php"); ?>

Thank you for hosting a game!

We just need a little bit of information from you to set this up.

		<form id="new-game">
			<input type="text" placeholder="Which game are you playing?" required>
			<input type="number" placeholder="How many people do you want?">
			<input type="text" placeholder="What platform are you playing on?" required>
			<input type="submit" value="Host this game">
		</form>
	<?php include("../include/footer.html"); ?>

Add another field to the host page Its important to know what platform you're playing on! Well, it can be. Also add required attributes where useful.


Latest Posts

		<?php
			global $post;
			$args = array( 'numberposts' => 5 );
			$myposts = get_posts( $args );
			foreach( $myposts as $post ) :
			setup_postdata($post);
		?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo the_time('jS F Y');?>

		<?php endforeach; ?>

Categories

		<?php
			$categories = get_categories();
			foreach ($categories as $category) {
				echo "
category_nicename}'>{$category->cat_name}
";
			}
		?>

Archive

			<?php wp_get_archives('type=yearly'); ?>

Latest Posts

		<?php
			global $post;
			$args = array( 'numberposts' => 5 );
			$myposts = get_posts( $args );
			foreach( $myposts as $post ) :
			setup_postdata($post);
		?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo the_time('jS F Y');?>

		<?php endforeach; ?>

Categories

		<?php
			$categories = get_categories();
      $base = get_bloginfo('url');
			foreach ($categories as $category) {
				echo "
category_nicename}'>{$category->cat_name}
";
			}
		?>

Archive

			<?php wp_get_archives('type=yearly'); ?>

Correct relative link to the categories

Correct relative link to the categories


<?php

require_once 'Swat/SwatContainer.php';

/**
 * Base class for containers that display an XHTML element
 *
 * @package   Swat
 * @copyright 2006 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatDisplayableContainer extends SwatContainer
{
	// {{{ public function display()

	/**
	 * Displays this container
	 */
	public function display()
	{
		if (!$this->visible)
			return;

		$div_tag = new SwatHtmlTag('div');
		$div_tag->id = $this->id;
		$div_tag->class = $this->getCSSClassString();

		$div->open();
		$this->displayChildren();
		$div->close();
	}

	// }}}
	// {{{ protected function getCSSClassNames()

	/**
	 * Gets the array of CSS classes that are applied to this displayable
	 * container
	 *
	 * @return array the array of CSS classes that are applied to this
	 *                displayable container.
	 */
	protected function getCSSClassNames()
	{
		$classes = array('swat-displayable-container');
		$classes = array_merge($classes, $this->classes);
		return $classes;
	}

	// }}}
}

?>

<?php

require_once 'Swat/SwatContainer.php';

/**
 * Base class for containers that display an XHTML element
 *
 * @package   Swat
 * @copyright 2006 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatDisplayableContainer extends SwatContainer
{
	// {{{ public function display()

	/**
	 * Displays this container
	 */
	public function display()
	{
		if (!$this->visible)
			return;

		$div = new SwatHtmlTag('div');
		$div->id = $this->id;
		$div->class = $this->getCSSClassString();

		$div->open();
		$this->displayChildren();
		$div->close();
	}

	// }}}
	// {{{ protected function getCSSClassNames()

	/**
	 * Gets the array of CSS classes that are applied to this displayable
	 * container
	 *
	 * @return array the array of CSS classes that are applied to this
	 *                displayable container.
	 */
	protected function getCSSClassNames()
	{
		$classes = array('swat-displayable-container');
		$classes = array_merge($classes, $this->classes);
		return $classes;
	}

	// }}}
}

?>

Fix misnamed SwatHtmltag
This was probably never caught because we seldom (if ever) use SwatDisplableContainer's own display() method

svn commit r10293


<?php

require_once 'Swat/SwatContainer.php';

/**
 * Base class for containers that display an XHTML element
 *
 * @package   Swat
 * @copyright 2006 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatDisplayableContainer extends SwatContainer
{
	// {{{ public properties

	/**
	 * The custom CSS class of this frame
	 *
	 * This optional class is added on top of the default 'swat-frame'
	 * class.
	 *
	 * @var string
	 */
	public $class = null;

	// }}}
	// {{{ protected function getCssClasses()

	/**
	 * Get CSS classes for outer XHTML element
	 */
	protected function getCssClasses($class)
	{
		if ($this->class !== null)
			$class.= ' '.$this->class;

		return $class;
	}

	// }}}
	// {{{ public function display()

	/**
	 * Displays this container
	 */
	public function display()
	{
		if (!$this->visible)
			return;

		$div = new SwatHtmlTag('div');
		$div->class = $this->getCssClasses('swat-displayable-container');

		if ($this->id !== null)
			$div->id = $this->id;

		$div->open();
		$this->displayChildren();
		$div->close();
	}

	// }}}
}

?>

<?php

require_once 'Swat/SwatContainer.php';

/**
 * Base class for containers that display an XHTML element
 *
 * @package   Swat
 * @copyright 2006 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatDisplayableContainer extends SwatContainer
{
	// {{{ public properties

	/**
	 * The custom CSS class of this container
	 *
	 * This optional class is added on top of the default 'swat-displayable-container'
	 * class.
	 *
	 * @var string
	 */
	public $class = null;

	// }}}
	// {{{ protected function getCssClasses()

	/**
	 * Get CSS classes for outer XHTML element
	 */
	protected function getCssClasses($class)
	{
		if ($this->class !== null)
			$class.= ' '.$this->class;

		return $class;
	}

	// }}}
	// {{{ public function display()

	/**
	 * Displays this container
	 */
	public function display()
	{
		if (!$this->visible)
			return;

		$div = new SwatHtmlTag('div');
		$div->class = $this->getCssClasses('swat-displayable-container');

		if ($this->id !== null)
			$div->id = $this->id;

		$div->open();
		$this->displayChildren();
		$div->close();
	}

	// }}}
}

?>

Use the correct class name.

Use the correct class name.

svn commit r7882


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

$id= (int)$_REQUEST['id'];

$type= $_REQUEST['type'];
$number= (int)$_REQUEST['number'];

if (!$id && $type) {
  $q= "SELECT id FROM txn
        WHERE type = '". $db->real_escape_string($type) ."'
          AND number = $number";
  $r= $db->query($q);

  if (!$r->num_rows)
    die_jsonp("No such transaction.");

  $row= $r->fetch_row();
  $id= $row[0];
}

if (!$id)
  die_jsonp("No transaction specified.");

$txn= txn_load($db, $id);

$items= txn_load_items($db, $id);

$payments= txn_load_payments($db, $id);

$notes= txn_load_notes($db, $id);

echo jsonp(array('txn' => $txn,
                 'items' => $items,
                 'payments' => $payments,
                 'notes' => $notes));

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

$id= (int)$_REQUEST['id'];

$type= $_REQUEST['type'];
$number= (int)$_REQUEST['number'];

if (!$id && $type) {
  $q= "SELECT id FROM txn
        WHERE type = '". $db->real_escape_string($type) ."'
          AND number = $number";
  $r= $db->query($q);

  if (!$r->num_rows)
    die_jsonp("No such transaction.");

  $row= $r->fetch_row();
  $id= $row[0];
}

if (!$id)
  die_jsonp("No transaction specified.");

echo jsonp(txn_load_full($db, $id));

Use txn_load_full() method so we get all the data we need


<?php

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

class CreateRoleUserTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('role_user', function(Blueprint $table)
    {
      $table->increments('id');

      $table->integer('role_id')->unsigned()->index();
      $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

      $table->integer('user_id')->unsigned()->index();
      $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

      $table->timestamps();
    });

  }

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

}

<?php

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

class CreateRoleUserTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('role_user', function(Blueprint $table)
    {
      $table->increments('id');
      $table->integer('role_id')->unsigned()->index();
      $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
      $table->integer('user_id')->unsigned()->index();
      $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

  }

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

}

Remove timestamps from role_user table

Remove timestamps from role_user table


<?php
namespace SxBootstrap\View\Helper\Bootstrap;

//use SxBootstrap\Exception;
use Zend\View\Helper\AbstractHelper;

/**
 * ViewHelper to add twitter bootstrap to the head.
 * This WILL use the headScript and headLink helpers.
 */
class Bootstrap extends AbstractHelper
{
    public function __invoke()
    {
        $this->prependCss();
        $this->prependJs();
    }

    protected function prependJs()
    {
        $this->getView()->headScript()->prependFile(
            $this->getView()->basePath() . '/js/bootstrap.js'
        );
    }

    protected function prependCss()
    {
        $this->getView()->headLink()->prependStylesheet(
            $this->getView()->basePath() . '/css/bootstrap.css'
        );
    }
}

<?php
namespace SxBootstrap\View\Helper\Bootstrap;

//use SxBootstrap\Exception;
use Zend\View\Helper\AbstractHelper;

/**
 * ViewHelper to add twitter bootstrap to the head.
 * This WILL use the headScript and headLink helpers.
 */
class Bootstrap extends AbstractHelper
{
    public function __invoke()
    {
        $this->prependCss();
        $this->prependJs();
    }

    protected function prependJs()
    {
        $scriptHelper = $this->view->plugin('head_script');
        $baseHelper   = $this->view->plugin('base_path');

        $scriptHelper->prependFile($baseHelper('/js/bootstrap.js'));
    }

    protected function prependCss()
    {
        $linkHelper = $this->view->plugin('head_link');
        $baseHelper = $this->view->plugin('base_path');

        $linkHelper->prependStylesheet($baseHelper('/css/bootstrap.css'));
    }
}

Use the plugin() method instead of __call()


<?php

$app['i18n']['en'] = [
    'layout' => [
        'code_placeholder'  => 'code',
        'save'              => 'Save',
        'code'              => 'Code',
        'title'             => 'Foler - single page translation system',
        'name'              => 'Name',
        'manage'            => 'Manage',
        'languages'         => 'Languages',
        'path'              => 'Path',
        'clear'             => 'Clear',
        'new_translation'   => 'Add new translation',
        'add_project'       => 'Add/edit project',
        'delete'            => 'delete'
        ],
    'foler' => [
        'project_saved' => 'Project saved'
    ]
];

Add correct i18n for layout

Add correct i18n for layout


<?php

namespace Tests;

use PHPUnit\Framework\TestCase;
use App\Contracts\SortingAlgorithm;

class AlgorithmTest extends TestCase
{
    /**
     * List of algorithms to test
     *
     * @var array
     */
    private $algorithms = [
        \App\Algorithms\BubbleSort::class,
        \App\Algorithms\MergeSort::class,
        \App\Algorithms\SelectionSort::class,
        \App\Algorithms\InsertionSort::class,
        \App\Algorithms\QuickSort::class,
    ];

    /**
     * Generate numbers to sort.
     */
    public function __construct() {
        $this->numbers = $this->sorted = range(1, 100);
        shuffle($this->numbers);
    }

    /**
     * Test each algorithm
     */
    public function testAlgorithms()
    {
        foreach ($this->algorithms as $algorithm) {
            // Assert it can really sort
            $this->assertAlgorithmCanSort(new $algorithm($this->numbers));

            // The original still must be shufled!
            $this->assertNotEquals($this->numbers, $this->sorted);
        }
    }

    /**
     * Check if given algorithm can sort
     *
     * @param  SortingAlgorithm $algorithm
     */
    private function assertAlgorithmCanSort(SortingAlgorithm $algorithm)
    {
        $actual = $algorithm->sort();
        $this->assertEquals($this->sorted, $actual);
    }
}

<?php

namespace Tests;

use PHPUnit\Framework\TestCase;
use App\Contracts\SortingAlgorithm;
use App\Contracts\ProvidesFeedback;

class AlgorithmTest extends TestCase
{

    /**
     * List of algorithms to test
     *
     * @var array
     */
    private $algorithms = [
        \App\Algorithms\BubbleSort::class,
        \App\Algorithms\MergeSort::class,
        \App\Algorithms\SelectionSort::class,
        \App\Algorithms\InsertionSort::class,
        \App\Algorithms\QuickSort::class,
    ];

    /**
     * Generate numbers to sort.
     */
    public function __construct()
    {
        $this->numbers = $this->sorted = range(1, 100);
        shuffle($this->numbers);
    }

    /**
     * Test each algorithm
     */
    public function testAlgorithms()
    {
        foreach ($this->algorithms as $algorithm) {
            $sorter = new $algorithm($this->numbers);

            // Assert it can really sort
            $this->assertAlgorithmCanSort($sorter);

            // The original still must be shufled!
            $this->assertNotEquals($this->numbers, $this->sorted);

            // Check if it implements and extends the neccessary interfaces and classes
            $this->assertInstanceOf(\App\Contracts\ProvidesFeedback::class, $sorter);
            $this->assertInstanceOf(\App\Sorter::class, $sorter);
        }
    }

    /**
     * Check if given algorithm can sort
     *
     * @param  SortingAlgorithm $algorithm
     */
    private function assertAlgorithmCanSort(SortingAlgorithm $algorithm)
    {
        $actual = $algorithm->sort();
        $this->assertEquals($this->sorted, $actual);
    }
}

Check interfaces, and abstract classes

Check interfaces, and abstract classes


<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
	<?php do_action( 'amp_post_template_head', $this ); ?>

<?php $this->load_parts( array( 'header-bar' ) ); ?>

<?php echo wp_kses_data( $this->get( 'post_title' ) ); ?>

		<?php $this->load_parts( apply_filters( 'amp_post_template_meta_parts', array( 'meta-author', 'meta-time', 'meta-taxonomy' ) ) ); ?>

	<?php echo $this->get( 'post_amp_content' ); // amphtml content; no kses ?>

<?php do_action( 'amp_post_template_footer', $this ); ?>

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

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
	<?php do_action( 'amp_post_template_head', $this ); ?>

<?php $this->load_parts( array( 'header-bar' ) ); ?>

<?php echo wp_kses_data( $this->get( 'post_title' ) ); ?>

		<?php $this->load_parts( apply_filters( 'amp_post_template_meta_parts', array( 'meta-author', 'meta-time', 'meta-taxonomy' ) ) ); ?>

	<?php echo $this->get( 'post_amp_content' ); // amphtml content; no kses ?>

<?php do_action( 'amp_post_template_footer', $this ); ?>

Add lang to `html` tag

Add lang to `html` tag

h/t shivampaw


#!/usr/bin/env php
<?php

if (empty($argv[1])) {
    fputs(STDERR, "1st argument is empty; Pass me a text file which contains file list\n");
    exit(1);
}
if (empty($argv[2])) {
    fputs(STDERR, "2nd argument is empty; Pass me a path to destination\n");
    exit(1);
}
$destination = trim($argv[2]);

$files = file_get_contents($argv[1]);
$files = explode("\n", $files);
$files = array_filter($files, 'strlen');

foreach ($files as $filepath) {
    $filepath = trim($filepath);
    if (is_file($filepath) || is_dir($filepath)) {
        $command    = sprintf("cp -a --parents %s %s 2>&1", $filepath, $destination);
        $output     = array();
        $return_var = 0;
        exec($command, $outout, $return_var);
        // echo $command, PHP_EOL;
        if ($return_var !== 0) {
            fputs(STDERR, $output[0]);
            exit(1);
        }
    } else {
        fputs(STDERR, "No such file or directory: $filepath\n");
        exit(1);
    }
}
exit(0);

#!/usr/bin/env php
<?php

/**
 * Last modified 2014-03-10
 * @author Ryo Utsunomiya (https://twitter.com/ryo511)
 */

if (empty($argv[1])) {
    fputs(STDERR, "1st argument is empty; Pass me a text file which contains file list\n");
    exit(1);
}
if (empty($argv[2])) {
    fputs(STDERR, "2nd argument is empty; Pass me a path to destination\n");
    exit(1);
}
$destination = trim($argv[2]);

$files = file_get_contents($argv[1]);
$files = explode("\n", $files);
$files = array_filter($files, 'strlen');

foreach ($files as $filepath) {
    $filepath = trim($filepath);
    if (is_file($filepath) || is_dir($filepath)) {
        $command    = sprintf("cp -a --parents %s %s 2>&1", $filepath, $destination);
        $output     = array();
        $return_var = 0;
        exec($command, $outout, $return_var);
        // echo $command, PHP_EOL;
        if ($return_var !== 0) {
            fputs(STDERR, $output[0]);
            exit(1);
        }
    } else {
        fputs(STDERR, "No such file or directory: $filepath\n");
        exit(1);
    }
}
exit(0);

Add Last Modified date and author

Add Last Modified date and author


<?php
/**
 * Part of CI PHPUnit Test
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2015 Kenji Suzuki
 * @link       https://github.com/kenjis/ci-phpunit-test
 */

$installer = new Installer();
$installer->install();

class Installer
{
    public static function install()
    {
        $test_folder = 'application/tests';
        static::recursiveCopy(
            'vendor/kenjis/ci-phpunit-test/application/tests',
            $test_folder
        );
    }

    /**
     * Recursive Copy
     *
     * @param string $src
     * @param string $dst
     */
    private static function recursiveCopy($src, $dst)
    {
        @mkdir($dst, 0755);

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($iterator as $file) {
            if ($file->isDir()) {
                @mkdir($dst . '/' . $iterator->getSubPathName());
            } else {
                $success = copy($file, $dst . '/' . $iterator->getSubPathName());
                if ($success) {
                    echo 'copied: ' . $dst . '/' . $iterator->getSubPathName() . PHP_EOL;
                }
            }
        }
    }
}

<?php
/**
 * Part of CI PHPUnit Test
 *
 * @author     Kenji Suzuki <https://github.com/kenjis>
 * @license    MIT License
 * @copyright  2015 Kenji Suzuki
 * @link       https://github.com/kenjis/ci-phpunit-test
 */

$installer = new Installer();
$installer->install();

class Installer
{
    public static function install()
    {
        $test_folder = 'application/tests';
        self::recursiveCopy(
            'vendor/kenjis/ci-phpunit-test/application/tests',
            $test_folder
        );
    }

    /**
     * Recursive Copy
     *
     * @param string $src
     * @param string $dst
     */
    private static function recursiveCopy($src, $dst)
    {
        @mkdir($dst, 0755);

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($iterator as $file) {
            if ($file->isDir()) {
                @mkdir($dst . '/' . $iterator->getSubPathName());
            } else {
                $success = copy($file, $dst . '/' . $iterator->getSubPathName());
                if ($success) {
                    echo 'copied: ' . $dst . '/' . $iterator->getSubPathName() . PHP_EOL;
                }
            }
        }
    }
}

Fix static and private combination

Fix static and private combination


<?php

namespace Nisaac2fly\AuthSamlWrapper\Laravel;

use Exception;

class Attributes {

    /**
     * @var array
     */
    protected $attributes = [];

    /**
     * @param array $attributes
     * @param User $user
     */
    function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    /**
     * Retrieve the given attribute.
     *
     * @param  string $key
     * @return string
     */
    public function get($key)
    {
        return array_get($this->attributes, $key);
    }

    /**
     * Determine if the given attribute exists.
     *
     * @param  string $key
     * @return boolean
     */
    public function has($key)
    {
        return array_key_exists($key, $this->attributes);
    }

    /**
     * Retrieve an array of all attributes.
     *
     * @return array
     */
    public function all()
    {
        return $this->attributes;
    }

    /**
     * Magic property access for attributes.
     *
     * @param  string $key
     * @return string
     * @throws Exception
     */
    public function __get($key)
    {
        if ($this->has($key)) {
            return $this->get($key);
        }

        throw new Exception("The {$key} attribute does not exist.");
    }
}

<?php

namespace Nisaac2fly\AuthSamlWrapper\Laravel;

use Exception;

class Attributes {

    /**
     * @var array
     */
    protected $attributes = [];

    /**
     * @param array $attributes
     * @param User $user
     */
    function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    /**
     * Retrieve the given attribute.
     *
     * @param  string $key
     * @return string
     */
    public function get($key)
    {
        return array_get($this->attributes, $key);
    }

    /**
     * Determine if the given attribute exists.
     *
     * @param  string $key
     * @return boolean
     */
    public function has($key)
    {
        return array_key_exists($key, $this->attributes);
    }

    /**
     * Retrieve an array of all attributes.
     *
     * @return array
     */
    public function all()
    {
        return $this->attributes;
    }

    /**
     * Magic property access for attributes.
     *
     * @param  string $key
     * @return string
     * @throws Exception
     */
    public function __get($key)
    {
        return $this->get($key);
    }
}

Remove exception when key doesn't exist just return null


<?php
class Kwf_User_AuthPassword_FnF extends Kwf_Model_FnF
{
    protected $_toStringField = 'email';
    protected $_hasDeletedFlag = true;

    protected function _init()
    {
        $this->_data = array(
            array('id'=>1, 'email' => 'test@vivid.com', 'password' => md5('foo'.'123'), 'password_salt' => '123', 'deleted'=>false),
            array('id'=>2, 'email' => 'testdel@vivid.com', 'password' => md5('bar'.'1234'), 'password_salt' => '1234', 'deleted'=>true),
        );
        parent::_init();
    }

    public function getAuthMethods()
    {
        return array(
            'password' => new Kwf_User_Auth_PasswordFields($this)
        );
    }
}

<?php
class Kwf_User_AuthPassword_FnF extends Kwf_Model_FnF
{
    protected $_toStringField = 'email';
    protected $_hasDeletedFlag = true;

    protected function _init()
    {
        $this->_data = array(
            array('id'=>1, 'email' => 'test@vivid.com', 'password' => md5('foo'.'123'), 'password_salt' => '123', 'deleted'=>false),
            array('id'=>2, 'email' => 'testdel@vivid.com', 'password' => md5('bar'.'1234'), 'password_salt' => '1234', 'deleted'=>true),
        );
        parent::_init();
    }

    public function getAuthMethods()
    {
        return array(
            'password' => new Kwf_User_Auth_PasswordFields($this),
            'activation' => new Kwf_User_Auth_ActivationFields($this),
        );
    }
}

Add activation auth method, needed for lost password in tests


<?php

/**
 * This file is part of the RequestStream package
 *
 * (c) Vitaliy Zhuk <zhuk2205@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 */

namespace RequestStream\Request\Web\Socket;

/**
 * Interface for control socket request
 */
interface RequestInterface
{
    /**
     * Set bind to
     *    Set other IP and port for request in our system
     *
     * @param string $ip
     *    Ip and port for connext
     *    Must be mask: ip:port
     *    Can use IPv4 and IPv6
     *
     * @see http://www.php.net/manual/en/context.socket.php
     */
    public function setBindTo($bindto);
}

<?php

/**
 * This file is part of the RequestStream package
 *
 * (c) Vitaliy Zhuk <zhuk2205@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 */

namespace RequestStream\Request\Web\Socket;

use RequestStream\Request\Web\WebInterface;

/**
 * Interface for control socket request
 */
interface RequestInterface extends WebInterface
{
    /**
     * Set bind to
     *    Set other IP and port for request in our system
     *
     * @param string $bindto
     * @see http://www.php.net/manual/en/context.socket.php
     */
    public function setBindTo($bindto);
}

Fix socket web request interface

Fix socket web request interface


<?php

declare(strict_types=1);

namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator;

use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\Exception\InvalidArgumentException;
use function array_map;
use function implode;

/**
 * The `staticProxyConstructor` implementation for null object proxies
 *
 */
class StaticProxyConstructor extends MethodGenerator
{
    /**
     * Constructor
     *
     * @param ReflectionClass $originalClass Reflection of the class to proxy
     *
     * @throws InvalidArgumentException
     */
    public function __construct(ReflectionClass $originalClass)
    {
        parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);

        $nullableProperties = array_map(
            function (ReflectionProperty $publicProperty) : string {
                return '$instance->' . $publicProperty->getName() . ' = null;';
            },
            Properties::fromReflectionClass($originalClass)->getPublicProperties()
        );

        $this->setReturnType($this->getName());
        $this->setDocBlock('Constructor for null object initialization');
        $this->setBody(
            'static $reflection;' . "\n\n"
            . '$reflection = $reflection ?? $reflection = new \ReflectionClass(__CLASS__);' . "\n"
            . '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n"
            . ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '')
            . 'return $instance;'
        );
    }
}

<?php

declare(strict_types=1);

namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator;

use ProxyManager\Generator\MethodGenerator;
use ProxyManager\ProxyGenerator\Util\Properties;
use ReflectionClass;
use ReflectionProperty;
use Zend\Code\Generator\Exception\InvalidArgumentException;
use function array_map;
use function implode;

/**
 * The `staticProxyConstructor` implementation for null object proxies
 *
 */
class StaticProxyConstructor extends MethodGenerator
{
    /**
     * Constructor
     *
     * @param ReflectionClass $originalClass Reflection of the class to proxy
     *
     * @throws InvalidArgumentException
     */
    public function __construct(ReflectionClass $originalClass)
    {
        parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC);

        $nullableProperties = array_map(
            function (ReflectionProperty $publicProperty) : string {
                return '$instance->' . $publicProperty->getName() . ' = null;';
            },
            Properties::fromReflectionClass($originalClass)->getPublicProperties()
        );

        $this->setReturnType($originalClass->getName());
        $this->setDocBlock('Constructor for null object initialization');
        $this->setBody(
            'static $reflection;' . "\n\n"
            . '$reflection = $reflection ?? $reflection = new \ReflectionClass(__CLASS__);' . "\n"
            . '$instance = $reflection->newInstanceWithoutConstructor();' . "\n\n"
            . ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '')
            . 'return $instance;'
        );
    }
}

Revert "Change return type hinting to reference the Proxy class"

This reverts commit 9ea4df8541c682097304bc9b1b42f68307f8d57e.


<?php

namespace Wnx\LaravelStats\Classifiers;

use Wnx\LaravelStats\ReflectionClass;
use Wnx\LaravelStats\Contracts\Classifier;

class ControllerClassifier implements Classifier
{
    public function getName()
    {
        return 'Controllers';
    }

    public function satisfies(ReflectionClass $class)
    {
        return collect(app('router')->getRoutes())
            ->reject(function ($route) {
                if (method_exists($route, 'getActionName')) {
                    return $route->getActionName() === 'Closure';
                }

                return data_get($route, 'action.uses') === null;
            })
            ->map(function ($route) {
                if (method_exists($route, 'getController')) {
                    return get_class($route->getController());
                }

                return str_before(data_get($route, 'action.uses'), '@');
            })
            ->unique()
            ->contains($class->getName());
    }
}

<?php

namespace Wnx\LaravelStats\Classifiers;

use Wnx\LaravelStats\ReflectionClass;
use Wnx\LaravelStats\Contracts\Classifier;

class ControllerClassifier implements Classifier
{
    public function getName()
    {
        return 'Controllers';
    }

    public function satisfies(ReflectionClass $class)
    {
        return collect(app('router')->getRoutes())
            ->reject(function ($route) {
                if (method_exists($route, 'getActionName')) {
                    // Laravel
                    return $route->getActionName() === 'Closure';
                }

                // Lumen
                return data_get($route, 'action.uses') === null;
            })
            ->map(function ($route) {
                if (method_exists($route, 'getController')) {
                    // Laravel
                    return get_class($route->getController());
                }

                // Lumen
                return str_before(data_get($route, 'action.uses'), '@');
            })
            ->unique()
            ->contains($class->getName());
    }
}

Add Comments to Controller Classifier

Add Comments to Controller Classifier


<?php

namespace RomansTest\Parser;

use PHPUnit\Framework\TestCase;
use Romans\Grammar\Grammar;
use Romans\Parser\Parser;

/**
 * Parser Test
 */
class ParserTest extends TestCase
{
    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->parser = new Parser();
    }

    /**
     * Test Grammar
     */
    public function testGrammar()
    {
        $grammar = new Grammar();

        $this->assertSame($this->parser, $this->parser->setGrammar($grammar));
        $this->assertSame($grammar, $this->parser->getGrammar());
    }

    /**
     * Test Parse
     */
    public function testParse()
    {
        $this->assertSame(1, $this->parser->parse([Grammar::T_I]));
        $this->assertSame(5, $this->parser->parse([Grammar::T_V]));
        $this->assertSame(10, $this->parser->parse([Grammar::T_X]));
    }
}

<?php

namespace RomansTest\Parser;

use PHPUnit\Framework\TestCase;
use Romans\Grammar\Grammar;
use Romans\Parser\Parser;

/**
 * Parser Test
 */
class ParserTest extends TestCase
{
    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->parser = new Parser();
    }

    /**
     * Test Grammar
     */
    public function testGrammar()
    {
        $grammar = new Grammar();

        $this->assertSame($this->parser, $this->parser->setGrammar($grammar));
        $this->assertSame($grammar, $this->parser->getGrammar());
    }

    /**
     * Test Parse
     */
    public function testParse()
    {
        $this->assertSame(1, $this->parser->parse([Grammar::T_I]));
        $this->assertSame(5, $this->parser->parse([Grammar::T_V]));
        $this->assertSame(10, $this->parser->parse([Grammar::T_X]));
    }

    /**
     * Test Parse with Multiple Tokens
     */
    public function testParseWithMultipleTokens()
    {
        $this->assertSame(6, $this->parser->parse([Grammar::T_V, Grammar::T_I]));
        $this->assertSame(13, $this->parser->parse([Grammar::T_X, Grammar::T_I, Grammar::T_I, Grammar::T_I]));
        $this->assertSame(111, $this->parser->parse([Grammar::T_C, Grammar::T_X, Grammar::T_I]));
    }
}

Include test with multiple tokens

Include test with multiple tokens


<?php
if (!class_exists('Cake\Http\Exception\ForbiddenException')) {
    class_alias(
        'Cake\Network\Exception\ForbiddenException',
        'Cake\Http\Exception\ForbiddenException'
    );

    class_alias(
        'Cake\Network\Exception\NotFoundException',
        'Cake\Http\Exception\NotFoundException'
    );
}

<?php
if (!class_exists('Cake\Http\Exception\ForbiddenException')) {
    class_alias(
        'Cake\Network\Exception\ForbiddenException',
        'Cake\Http\Exception\ForbiddenException'
    );
}
if (!class_exists('Cake\Http\Exception\NotFoundException')) {
    class_alias(
        'Cake\Network\Exception\NotFoundException',
        'Cake\Http\Exception\NotFoundException'
    );
}

Make plugin compatible with FoC/Crud

Make plugin compatible with FoC/Crud

They made a similar solution: https://github.com/FriendsOfCake/crud/blob/master/aliases.php

however I get following error
```
PHP Warning:  Cannot declare class Cake\Http\Exception\NotFoundException, because the name is already in use in /var/www/apacta/vendor/friendsofcake/crud/aliases.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/apacta/vendor/phpunit/phpunit/phpunit:0
PHP   2. require() /var/www/apacta/vendor/phpunit/phpunit/phpunit:51
PHP   3. ComposerAutoloaderInitc5f18fedf80ea89a4186f61d865fa6d8::getLoader() /var/www/apacta/vendor/autoload.php:7
PHP   4. composerRequirec5f18fedf80ea89a4186f61d865fa6d8() /var/www/apacta/vendor/composer/autoload_real.php:56
PHP   5. require() /var/www/apacta/vendor/composer/autoload_real.php:66
PHP   6. class_alias() /var/www/apacta/vendor/friendsofcake/crud/aliases.php:17
```


@extends("layout.base")

@section("title", "Wdi Paste - {$paste->name}")

@section("container")

{{ $paste->name }}.{{$paste->extension}}

{{ $paste->description }}

            Creato il {{ $paste->created_at }} Linguaggio:
            language->name) }}">{{ $paste->language->name }}

{{ $paste->code }}

@endsection

@section("js")

@endsection

Move code content to center of view

Move code content to center of view


<?php

namespace PHPFastCGI\FastCGIDaemon\Driver;

class DriverContainer implements DriverContainerInterface
{
    /**
     * @var array
     */
    private $drivers;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->drivers = [
            'userland' => [
                'object'    => null,
                'classPath' => 'PHPFastCGI\FastCGIDaemon\Driver\Userland\UserlandDaemonFactory',
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFactory($driver)
    {
        if (!isset($this->drivers[$driver])) {
            throw new \InvalidArgumentException('Unknown driver: '.$driver);
        }

        if (null === $this->drivers[$driver]['object']) {
            $this->drivers[$driver]['object'] = new $this->drivers[$driver]['classPath']();
        }

        return $this->drivers[$driver]['object'];
    }
}

<?php

namespace PHPFastCGI\FastCGIDaemon\Driver;

class DriverContainer implements DriverContainerInterface
{
    /**
     * @var array
     */
    private $drivers;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->drivers = [
            'userland' => [
                'object'    => null,
                'classPath' => 'PHPFastCGI\FastCGIDaemon\Driver\Userland\UserlandDaemonFactory',
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFactory($driver)
    {
        if (!isset($this->drivers[$driver])) {
            throw new \InvalidArgumentException('Unknown driver: '.$driver);
        }

        if (null === $this->drivers[$driver]['object']) {
            $class = $this->drivers[$driver]['classPath'];
            $this->drivers[$driver]['object'] = new $class();
        }

        return $this->drivers[$driver]['object'];
    }
}

Make IDE stop complaining about syntax error


<?php

namespace Banklink\Request;

/**
 * Generic request representation
 *
 * @author Roman Marintsenko <inoryy@gmail.com>
 * @since  31.10.2012
 */
abstract class Request
{
    protected $requestUrl;
    protected $requestData = array();

    /**
     * @param string $requestUrl
     * @param array  $requestData
     */
    public function __construct($requestUrl, array $requestData)
    {
        $this->requestUrl  = $requestUrl;
        $this->requestData = $requestData;
    }

    /**
     * Get request data which should be sent to desired bank
     *
     * @return array
     */
    public function getRequestData()
    {
        return $this->requestData;
    }

    /**
     * Generates HTML view for request <input> fields
     * NB! This does not generate actual <form> element, it must be rendered manually
     *
     * @return string
     */
    public function buildRequestHtml()
    {
        $output = '';

        foreach ($this->requestData as $key => $value) {
            $output .= sprintf('<input id="%s" name="%s" value="%s" type="hidden" />', strtolower($key), $key, $value);
        }

        return $output;
    }

    /**
     * Get URL to where request data should be sent (most likely via POST method)
     *
     * @return string
     */
    public function getRequestUrl()
    {
        return $this->requestUrl;
    }
}

<?php

namespace Banklink\Request;

/**
 * Generic request representation
 *
 * @author Roman Marintsenko <inoryy@gmail.com>
 * @since  31.10.2012
 */
abstract class Request
{
    protected $requestUrl;
    protected $requestData = array();

    /**
     * @param string $requestUrl
     * @param array  $requestData
     */
    public function __construct($requestUrl, array $requestData)
    {
        $this->requestUrl  = $requestUrl;
        $this->requestData = $requestData;
    }

    /**
     * Get request data which should be sent to desired bank
     *
     * @return array
     */
    public function getRequestData()
    {
        return $this->requestData;
    }

    /**
     * Generates HTML view for request <input> fields
     * NB! This does not generate actual <form> element, it must be rendered manually
     *
     * @return string
     */
    public function buildRequestHtml()
    {
        $output = '';

        foreach ($this->requestData as $key => $value) {
            $output .= sprintf('<input name="%s" value="%s" type="hidden" />', strtolower($key), $key, $value);
        }

        return $output;
    }

    /**
     * Get URL to where request data should be sent (most likely via POST method)
     *
     * @return string
     */
    public function getRequestUrl()
    {
        return $this->requestUrl;
    }
}

Remove id attribute from input

Remove id attribute from input


<?php

namespace Plummer\Calendarful\Calendar;

class CalendarFactory implements CalendarFactoryInterface
{
	private $calendarTypes = [];

	public function addCalendarType($type, $calendarType)
	{
		if(is_string($calendarType) and !class_exists($calendarType)) {
			throw new \InvalidArgumentException("Class {$calendarType} des not exist.");
		}
		else if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType, false))) {
			throw new \InvalidArgumentException('File or File path required.');
		}

		$this->calendarTypes[$type] = is_string($calendarType) ?
			$calendarType :
			get_class($calendarType);
	}

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

	public function createCalendar($type)
	{
		if(!isset($this->calendarTypes[$type])) {
			throw new \Exception('The type passed does not exist.');
		}

		$calendar = new $this->calendarTypes[$type]();

		return $calendar;
	}
}

<?php

namespace Plummer\Calendarful\Calendar;

class CalendarFactory implements CalendarFactoryInterface
{
	private $calendarTypes = [];

	public function addCalendarType($type, $calendarType)
	{
		if(is_string($calendarType) and !class_exists($calendarType)) {
			throw new \InvalidArgumentException("Class {$calendarType} des not exist.");
		}
		else if(!in_array('Plummer\Calendarful\Calendar\CalendarInterface', class_implements($calendarType, false))) {
			throw new \InvalidArgumentException('File or File path required.');
		}

		$this->calendarTypes[$type] = is_string($calendarType) ?
			$calendarType :
			get_class($calendarType);
	}

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

	public function createCalendar($type)
	{
		if(!isset($this->calendarTypes[$type])) {
			throw new \OutOfBoundsException("A calendar type called {$type} does not exist within the factory.");
		}

		$calendar = new $this->calendarTypes[$type]();

		return $calendar;
	}
}

Make exception more specific when retrieving a calendar type that does not exist in the calendar factory.


<?php

namespace FaimfonyBundle\Form;

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

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('is_cooker', CheckboxType::class, array(
            'label'     => 'Voulez-vous devenir un Cooker ?',
            'required'  => false
            ))
            ->add('email', null, array('label'=>'Votre e-mail:'))
            ->add('first_name', null, array('label'=>'Prénom:'))
            ->add('lastname', null, array('label'=>'Nom:'))
            ->add('phone', null, array('label'=>'Numéro de téléphone:'))
            ->remove('username');
    }

    public function getParent()
    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';

    }

    public function getBlockPrefix()
    {
        return 'app_user_registration';
    }

    // For Symfony 2.x
    public function getName()
    {
        return $this->getBlockPrefix();
    }
}

<?php

namespace FaimfonyBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('is_cooker', CheckboxType::class, array(
            'label'     => 'Voulez-vous devenir un Cooker ?',
            'required'  => false
            ))
            ->add('email', null, array('label'=>'Votre e-mail:'))
            ->add('first_name', null, array('label'=>'Prénom:'))
            ->add('lastname', null, array('label'=>'Nom:'))
            ->add('phone', null, array('label'=>'Numéro de téléphone:'))
            ->remove('username');
    }

    public function getParent()
    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';

    }

    public function getBlockPrefix()
    {
        return 'app_user_registration';
    }

    // For Symfony 2.x
    public function getName()
    {
        return $this->getBlockPrefix();
    }
}

Add Sonata Debug : user_type in RegistrationForm2


<?php namespace Anomaly\PagesModule\Page\Form;

use Anomaly\PagesModule\Page\Command\GetRealPath;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;

/**
 * Class PageFormFields
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\PagesModule\Page\Form
 */
class PageFormFields implements SelfHandling
{

    use DispatchesJobs;

    public function handle(PageFormBuilder $builder)
    {
        $type   = $builder->getType();
        $parent = $builder->getParent();

        /* @var PageInterface $entry */
        if ($entry = $builder->getFormEntry()) {
            $parent = $entry->getParent();
        }

        $builder->setFields(
            [
                '*',
                'slug'         => [
                    'config' => [
                        'prefix' => ($parent ? url($this->dispatch(new GetRealPath($parent))) : url()) . '/'
                    ]
                ],
                'theme_layout' => [
                    'config' => [
                        'default_value' => $type ? $type->getThemeLayout() : null
                    ]
                ]
            ]
        );
    }
}

<?php namespace Anomaly\PagesModule\Page\Form;

use Anomaly\PagesModule\Page\Command\GetRealPath;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;

/**
 * Class PageFormFields
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\PagesModule\Page\Form
 */
class PageFormFields implements SelfHandling
{

    use DispatchesJobs;

    /**
     * Handle the page fields.
     *
     * @param PageFormBuilder $builder
     */
    public function handle(PageFormBuilder $builder)
    {
        $type   = $builder->getType();
        $parent = $builder->getParent();

        /* @var PageInterface $entry */
        if (!$parent && $entry = $builder->getFormEntry()) {
            $parent = $entry->getParent();
        }

        $builder->setFields(
            [
                '*',
                'slug'         => [
                    'config' => [
                        'prefix' => ($parent ? url($this->dispatch(new GetRealPath($parent))) : url()) . '/'
                    ]
                ],
                'theme_layout' => [
                    'config' => [
                        'default_value' => $type ? $type->getThemeLayout() : null
                    ]
                ]
            ]
        );
    }
}

Fix issue where parent slug was not being included on NEW entries


<?php

namespace TuxOne\ValidationBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * @Annotation
 */
class NotContainsBadWordsValidator extends ConstraintValidator
{
    private $dictionaryPath;

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

    }

    public function validate($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $stringValue = (string) $value;

        // Load blacklist
        $blacklist = $this->getBlackListArray();

        // Split input value into words
        $words = $this->getWordsArray($stringValue);

        // Search for bad words
        $match = array_intersect($words, $blacklist);

        if ( count($match) > 0 ) {
            $this->context->addViolation($constraint->message, array('%string%' => reset($match)));
        }
    }

    private function getBlackListArray()
    {
        return file(__DIR__."/../../Dictionaries/list.txt", FILE_IGNORE_NEW_LINES);
    }

    private function getWordsArray($text)
    {
        $text = strtolower($text);
        $text = preg_replace("/[^a-z0-9 ]/", ' ', $text);
        $words = explode(' ', $text);
        $words = array_unique($words);
        return $words;
    }
}

<?php

namespace TuxOne\ValidationBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * @Annotation
 */
class NotContainsBadWordsValidator extends ConstraintValidator
{
    private $dictionaryPath;

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

    }

    public function validate($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $stringValue = (string) $value;

        // Load blacklist
        $blacklist = $this->getBlackListArray();

        // Split input value into words
        $words = $this->getWordsArray($stringValue);

        // Search for bad words
        $match = array_intersect($words, $blacklist);

        if ( count($match) > 0 ) {
            $this->context->addViolation($constraint->message, array('%string%' => reset($match)));
        }
    }

    private function getBlackListArray()
    {
        return file($this->dictionaryPath, FILE_IGNORE_NEW_LINES);
    }

    private function getWordsArray($text)
    {
        $text = strtolower($text);
        $text = preg_replace("/[^a-z0-9 ]/", ' ', $text);
        $words = explode(' ', $text);
        $words = array_unique($words);
        return $words;
    }
}

Replace the hard coded dictionary path with a variable.


<?php

namespace Bloge\Renderers;

use Bloge\NotFoundException;

/**
 * Basic renderer
 *
 * This renderer renders raw PHP templates
 *
 * @package bloge
 */
class PHP implements IRenderer
{
    /**
     * @var string $path
     */
    protected $path;

    /**
     * @var array $data
     */
    protected $data = [];

    /**
     * @param string $path
     */
    public function __construct($path)
    {
        $this->path = chop($path, '/');
    }

    /**
     * @param string $view
     * @param array $data
     * @return string
     */
    public function partial($view, array $data = [])
    {
        $view = \Bloge\removeExtension($view);
        $path = "{$this->path}/$view.php";

        if (!file_exists($path)) {
            throw new NotFoundException($view);
        }

        return \Bloge\render($path, array_merge($this->data, $data));
    }

    /**
     * @{inheritDoc}
     */
    public function render(array $data = [])
    {
        $layout = isset($data['layout'])
            ? $data['layout']
            : 'layout.php';

        $data['theme'] = $this;
        $this->data = $data;

        return $this->partial($layout, $data);
    }
}

<?php

namespace Bloge\Renderers;

use Bloge\NotFoundException;

/**
 * Basic renderer
 *
 * This renderer renders raw PHP templates
 *
 * @package bloge
 */
class PHP implements IRenderer
{
    /**
     * @var string $path
     */
    protected $path;

    /**
     * @var array $data
     */
    protected $data = [];

    /**
     * @param string $path
     */
    public function __construct($path)
    {
        $this->path = chop($path, '/');
    }

    /**
     * @param string $view
     * @param array $data
     * @return string
     */
    public function partial($view, array $data = [])
    {
        $data['theme'] = $this;
        $view = \Bloge\removeExtension($view);
        $path = "{$this->path}/$view.php";

        if (!file_exists($path)) {
            throw new NotFoundException($view);
        }

        return \Bloge\render($path, array_merge($this->data, $data));
    }

    /**
     * @{inheritDoc}
     */
    public function render(array $data = [])
    {
        $this->data = $data;
        $layout = isset($data['layout'])
            ? $data['layout']
            : 'layout';

        return $this->partial($layout, $data);
    }
}

Move '$theme' injection in partial method


<?php
namespace Sendworks;

class ServicePointsCollection {
  protected $connection;

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

  function select($product, $recipient, $limit = null) {
    $query = [];
    if ($product instanceOf Product) {
      $query['product_code'] = $product->code;
    } else {
      $query['product_code'] = $product;
    }
    if ($limit) {
      $query['limit'] = $limit;
    }
    $query['street1'] = $recipient->street1;
    $query['street2'] = $recipient->street2;
    $query['city'] = $recipient->city;
    $query['post_code'] = $recipient->post_code;
    $query['region'] = $recipient->region;
    $query['country_code'] = $recipient->country_code;
    $response = $this->client()->get('service_points', ['query' => $query]);
    $result = array();
    foreach (json_decode($response->getBody(), true) as $struct) {
      $result[] = new ServicePoint($struct);
    }
    return $result;
  }

  protected function client() {
    return $this->connection->client();
  }
}

<?php
namespace Sendworks;

class ServicePointsCollection {
  protected $connection;

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

  function find($product, $reference) {
    $query = [];
    if ($product instanceOf Product) {
      $product_code = $product->code;
    } else {
      $product_code = $product;
    }
    if ($reference instanceOf ServicePoint) {
      $reference = $reference->reference;
    }
    $response = $this->client()->get(implode('/', array('service_points', urlencode($product_code), urlencode($reference))));
    return new ServicePoint(json_decode($response->getBody(), true));
  }

  function select($product, $recipient, $limit = null) {
    $query = [];
    if ($product instanceOf Product) {
      $query['product_code'] = $product->code;
    } else {
      $query['product_code'] = $product;
    }
    if ($limit) {
      $query['limit'] = $limit;
    }
    $query['street1'] = $recipient->street1;
    $query['street2'] = $recipient->street2;
    $query['city'] = $recipient->city;
    $query['post_code'] = $recipient->post_code;
    $query['region'] = $recipient->region;
    $query['country_code'] = $recipient->country_code;
    $response = $this->client()->get('service_points', ['query' => $query]);
    $result = array();
    foreach (json_decode($response->getBody(), true) as $struct) {
      $result[] = new ServicePoint($struct);
    }
    return $result;
  }

  protected function client() {
    return $this->connection->client();
  }
}

Support for pulling out a single service point by product + reference


<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class RegistrationController extends Controller
{
    /**
     * @Route("/inscription", name="registration")
     * @Method({"GET","POST"})
     */
    public function registrationAction(Request $request)
    {
        return $this->render('registration.html.twig');
    }
}

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class RegistrationController extends Controller
{
    /**
     * @Route("/inscription", name="registration")
     * @Method({"GET","POST"})
     */
    public function registrationAction(Request $request)
    {
        // Only for user not logged
        if($this->getUser()){
            return $this->redirectToRoute('homepage');
        }

        return $this->render('registration.html.twig');
    }
}

Refactor (Registration Controller): Define security acces level


<?php
$nav = array(
	"List" => "file/upload_history",
	"Thumbnails" => "file/upload_history_thumbnails",
);

$CI =& get_instance();

foreach ($nav as $key => $item) {
	?>
		<li <?php echo $CI->uri->uri_string() == $item ? 'class="active"' : ''; ?>>
			<a href="<?php echo site_url($item); ?>"><?php echo $key; ?>

	<?php
}
?>

Revert upload_history tabs to tabs instead of pills

Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>


<?php

namespace geotime\Test;

use PHPUnit_Framework_TestCase;
use geotime\models\Map;

class MapTest extends \PHPUnit_Framework_TestCase {

    static function setUpBeforeClass() {
        Map::$log->info(__CLASS__." tests started");
    }

    static function tearDownAfterClass() {
        Map::$log->info(__CLASS__." tests ended");
    }

    public function testGenerateMap() {
        $date1Str = '2011-01-02';
        $date2Str = '2013-07-15';
        $imageFileName = 'testImage.svg';

        $map = Map::generateAndSaveReferences($imageFileName, $date1Str, $date2Str);
        $this->assertNotNull($map);
        $this->assertEquals($imageFileName, $map->getFileName());

        $territoriesWithPeriods = $map->getTerritoriesWithPeriods();
        $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getStart());
        $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getEnd());
    }
}

<?php

namespace geotime\Test;

use PHPUnit_Framework_TestCase;
use geotime\models\Map;
use geotime\Database;

class MapTest extends \PHPUnit_Framework_TestCase {

    static function setUpBeforeClass() {
        Map::$log->info(__CLASS__." tests started");
    }

    static function tearDownAfterClass() {
        Map::$log->info(__CLASS__." tests ended");
    }

    protected function setUp() {
        Database::connect("geotime_test");
    }

    public function testGenerateMap() {
        $date1Str = '2011-01-02';
        $date2Str = '2013-07-15';
        $imageFileName = 'testImage.svg';

        $map = Map::generateAndSaveReferences($imageFileName, $date1Str, $date2Str);
        $this->assertNotNull($map);
        $this->assertEquals($imageFileName, $map->getFileName());

        $territoriesWithPeriods = $map->getTerritoriesWithPeriods();
        $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getStart());
        $this->assertInstanceOf('MongoDate', $territoriesWithPeriods[0]->getPeriod()->getEnd());
    }
}

Fix database connection in test

Fix database connection in test


<?php
//exit;
/* connector for Turbellarian
estimated execution time: 2 hrs.
This connector gets data from website and rank information from a csv file.
*/

$timestart = microtime(1);

include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/TurbellarianAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = TurbellarianAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "185.xml";

$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec              \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min   \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");

?>

<?php
exit;
/* connector for Turbellarian
estimated execution time: 18 hrs.
This connector gets data from website and rank information from a csv file.
*/

$timestart = microtime(1);

include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/TurbellarianAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = TurbellarianAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "185.xml";

$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec              \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min   \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");

?>

Disable connector to run in beast.

Disable connector to run in beast.

git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1410 baf6b65b-9124-4dc3-b1c0-01155b4af546


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for sort Mimic library function.
 *
 * @since 0.1.0
 */
class SortFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(false, F\sortable(), array(4, 2, 1, 3), array(1, 2, 3, 4)),
			array(true, F\sortable(), array(4, 2, 1, 3), array(2 => 1, 1 => 2, 3 => 3, 0 => 4)),
			array(false, 'strcasecmp',
				array('2', '1', 'world', 'hello'),
				array('1', '2', 'hello', 'world')
			),
			array(true, 'strcasecmp',
				array('2', '1', 'world', 'hello'),
				array(2 => '1', 0 => '2', 4 => 'hello', 3 => 'world')
			),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\sort
	 */
	public function testResults($preserveKeys, $callback, $collection, $expected) {
		$this->assertEquals($expected, F\sort($collection, $callback, $preserveKeys));
	}
}

<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for sort Mimic library function.
 *
 * @since 0.1.0
 */
class SortFuncTest extends PHPUnit_Framework_TestCase {
	public function dataProvider() {
		return array(
			array(false, F\sortable(), array(4, 2, 1, 3), array(1, 2, 3, 4)),
			array(true, F\sortable(), array(4, 2, 1, 3), array(2 => 1, 1 => 2, 3 => 3, 0 => 4)),
			array(false, F\sortable(),
				array('2', '1', 'world', 'hello'),
				array('1', '2', 'hello', 'world')
			),
			array(true, F\sortable(),
				array('2', '1', 'world', 'hello'),
				array(2 => '1', 0 => '2', 4 => 'hello', 3 => 'world')
			),
		);
	}

	/**
	 * @dataProvider dataProvider
	 * @covers ::Mimic\Functional\sort
	 */
	public function testResults($preserveKeys, $callback, $collection, $expected) {
		$this->assertEquals($expected, F\sort($collection, $callback, $preserveKeys));
	}
}

Fix test: use sortable because builtin does not accept third parameter.


<?php declare(strict_types=1);

namespace Gos\Bundle\WebSocketBundle\Client;

use Ratchet\ConnectionInterface;
use Ratchet\Wamp\Topic;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

interface ClientManipulatorInterface
{
    /**
     * @return ClientConnection[]
     */
    public function findAllByUsername(Topic $topic, string $username): array;

    /**
     * @return ClientConnection[]
     */
    public function findByRoles(Topic $topic, array $roles): array;

    /**
     * @return ClientConnection[]
     */
    public function getAll(Topic $topic, bool $anonymous = false): array;

    public function getClient(ConnectionInterface $connection): TokenInterface;

    /**
     * @return string|object
     */
    public function getUser(ConnectionInterface $connection);
}

<?php declare(strict_types=1);

namespace Gos\Bundle\WebSocketBundle\Client;

use Ratchet\ConnectionInterface;
use Ratchet\Wamp\Topic;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

interface ClientManipulatorInterface
{
    /**
     * @return ClientConnection[]
     */
    public function findAllByUsername(Topic $topic, string $username): array;

    /**
     * @return ClientConnection[]
     */
    public function findByRoles(Topic $topic, array $roles): array;

    /**
     * @return ClientConnection[]
     */
    public function getAll(Topic $topic, bool $anonymous = false): array;

    public function getClient(ConnectionInterface $connection): TokenInterface;

    /**
     * @return string|\Stringable|UserInterface
     */
    public function getUser(ConnectionInterface $connection);
}

Update the client manipulator interface's user return to match up with the security token types