<?php

namespace Stevenmaguire\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class KeycloakResourceOwner implements ResourceOwnerInterface
{
    /**
     * Raw response
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new resource owner.
     *
     * @param array  $response
     */
    public function __construct(array $response = array())
    {
        $this->response = $response;
    }

    /**
     * Get resource owner id
     *
     * @return string|null
     */
    public function getId()
    {
        return $this->response['sub'] ?: null;
    }

    /**
     * Get resource owner email
     *
     * @return string|null
     */
    public function getEmail()
    {
        return $this->response['email'] ?: null;
    }

    /**
     * Get resource owner name
     *
     * @return string|null
     */
    public function getName()
    {
        return $this->response['name'] ?: null;
    }

    /**
     * Return all of the owner details available as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->response;
    }
}

<?php

namespace Stevenmaguire\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class KeycloakResourceOwner implements ResourceOwnerInterface
{
    /**
     * Raw response
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new resource owner.
     *
     * @param array  $response
     */
    public function __construct(array $response = array())
    {
        $this->response = $response;
    }

    /**
     * Get resource owner id
     *
     * @return string|null
     */
    public function getId()
    {
        return $this->response['sub'] ?? null;
    }

    /**
     * Get resource owner email
     *
     * @return string|null
     */
    public function getEmail()
    {
        return $this->response['email'] ?? null;
    }

    /**
     * Get resource owner name
     *
     * @return string|null
     */
    public function getName()
    {
        return $this->response['name'] ?? null;
    }

    /**
     * Return all of the owner details available as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->response;
    }
}

Fix Warning: Undefined array key on PHP8


<?php

use Biome\Core\Controller;
use Biome\Core\Collection;

class BaseController extends Controller
{
	public function beforeRoute()
	{
		/**
		 * Check route rights.
		 */
		$this->checkAuthorizations();

		/**
		 * Check authentication.
		 */
		$auth = Collection::get('auth');
		if(!$auth->isAuthenticated())
		{
			$this->response()->redirect('');
			return FALSE;
		}

		return TRUE;
	}
}

<?php

use Biome\Core\Controller;
use Biome\Core\Collection;

class BaseController extends Controller
{
	public function beforeRoute()
	{
		/**
		 * Check route rights.
		 */
		$this->checkAuthorizations();

		/**
		 * Check authentication.
		 */
		$auth = Collection::get('auth');
		if(!$auth->isAuthenticated())
		{
			$this->flash()->error('Forbidden!');
			$this->response()->redirect('');
			return FALSE;
		}

		return TRUE;
	}
}

Add a flash message on forbidden.

Add a flash message on forbidden.


<?php

namespace BNETDocs\Views\Document;

use \BNETDocs\Models\Document\Index as DocumentIndexModel;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\Exceptions\IncorrectModelException;
use \CarlBennett\MVC\Libraries\Model;
use \CarlBennett\MVC\Libraries\View;

class IndexJSON extends View {

  public function getMimeType() {
    return 'application/json;charset=utf-8';
  }

  public function render(Model &$model) {
    if (!$model instanceof DocumentIndexModel) {
      throw new IncorrectModelException();
    }
    echo json_encode([
      'users' => $model->users
    ], Common::prettyJSONIfBrowser());
  }

}

<?php

namespace BNETDocs\Views\Document;

use \BNETDocs\Models\Document\Index as DocumentIndexModel;
use \CarlBennett\MVC\Libraries\Common;
use \CarlBennett\MVC\Libraries\Exceptions\IncorrectModelException;
use \CarlBennett\MVC\Libraries\Model;
use \CarlBennett\MVC\Libraries\View;

class IndexJSON extends View {

  public function getMimeType() {
    return 'application/json;charset=utf-8';
  }

  public function render(Model &$model) {
    if (!$model instanceof DocumentIndexModel) {
      throw new IncorrectModelException();
    }
    echo json_encode([
      'documents' => $model->documents
    ], Common::prettyJSONIfBrowser());
  }

}

Fix another bug introduced in 1ef6e27

Fix another bug introduced in 1ef6e27


<?php

return [
    'es_ES.utf8' => 'Español',
    'es_AR.utf8' => 'Español Argentina',
    # 'en_US.utf8' => 'English',
];

<?php

return [
    'en_US.utf8' => 'English',
    'es_ES.utf8' => 'Español',
    'es_AR.utf8' => 'Español Argentina',
    # 'en_US.utf8' => 'English',
];

Add en_US.utf-8 to language selection menu


<?php namespace TeamWorkPm;

class Auth
{
    const URL = 'https://authenticate.teamworkpm.net/';

    private static $config = [
        'url' => null,
        'key' => null
    ];

    public static function set()
    {
        $num_args = func_num_args();
        if ($num_args === 1) {
            self::$config['url'] = self::$url;
            self::$config['key'] = func_get_arg(0);
            self::$config['url'] = Factory::build('account')->authenticate()->url;
        } elseif ($num_args === 2) {
            self::$config['url'] = $url = func_get_arg(0);
            if ($is_subdomain = (strpos($url, '.') === false)) {
                self::$config['url'] = self::URL;
            }
            self::$config['key']  = func_get_arg(1);
            if ($is_subdomain) {
                $url = Factory::build('account')->authenticate()->url;
            }
            self::$config['url'] = $url;
        }
    }

    public static function get()
    {
        return array_values(self::$config);
    }
}

<?php namespace TeamWorkPm;

class Auth
{
    const URL = 'https://authenticate.teamworkpm.net/';

    private static $config = [
        'url' => null,
        'key' => null
    ];

    public static function set()
    {
        $num_args = func_num_args();
        if ($num_args === 1) {
            self::$config['url'] = self::URL;
            self::$config['key'] = func_get_arg(0);
            self::$config['url'] = Factory::build('account')->authenticate()->url;
        } elseif ($num_args === 2) {
            self::$config['url'] = $url = func_get_arg(0);
            if ($is_subdomain = (strpos($url, '.') === false)) {
                self::$config['url'] = self::URL;
            }
            self::$config['key']  = func_get_arg(1);
            if ($is_subdomain) {
                $url = Factory::build('account')->authenticate()->url;
            }
            self::$config['url'] = $url;
        }
    }

    public static function get()
    {
        return array_values(self::$config);
    }
}

Fix fatal error when setting API key

Fix fatal error when setting API key

No such property $url, updated to use constant


<?php declare(strict_types=1); # -*- coding: utf-8 -*-

namespace Bueltge\Marksimple\Tests\Unit\Rule;

use Bueltge\Marksimple\Rule;
use Bueltge\Marksimple\Rule\ElementRuleInterface;
use Bueltge\Marksimple\Tests\Unit\AbstractRuleTestCase;

class StrongTest extends AbstractRuleTestCase
{

    public function provideList(): array
    {
        return [ /* TODO */];
    }

    public function returnRule(): ElementRuleInterface
    {
        return new Rule\Strong();
    }
}

<?php declare(strict_types=1); # -*- coding: utf-8 -*-

namespace Bueltge\Marksimple\Tests\Unit\Rule;

use Bueltge\Marksimple\Rule;
use Bueltge\Marksimple\Rule\ElementRuleInterface;
use Bueltge\Marksimple\Tests\Unit\AbstractRuleTestCase;

class StrongTest extends AbstractRuleTestCase
{

    public function provideList(): array
    {
        return [
            'star' => ['**Strong word**', 'Strong word'],
            'underline' => ['__Strong word__', 'Strong word'],
        ];
    }

    public function returnRule(): ElementRuleInterface
    {
        return new Rule\Strong();
    }
}

Add simple test for strong

Add simple test for strong


<?php namespace Exolnet\Core;

class EnvironmentDetector
{
	private static $environments = [
		'development.exolnet.com' => 'local',
		'staging.exolnet.com'     => 'staging',
		'testing.exolnet.com'     => 'staging',
	];

	/**
	 * @param $environments
	 * @return callable
	 */
	public static function detect($environments)
	{
		// TODO: Do not allow $is_behat = true in production environment
		$is_behat = self::is_remote_test();
		if ($is_behat) {
			return function() { return 'test'; };
		}

		if (isset($_SERVER['HTTP_HOST']))
		{
			$host = $_SERVER['HTTP_HOST'];

			if (array_key_exists($host, self::$environments)) {
				return function() use ($host) { return self::$environments[$host]; };
			}
		}

		return $environments;
	}

	/**
	 * @return bool
	 */
	public static function is_remote_test()
	{
		return array_get($_COOKIE, 'test-env') === 'true';
	}
}

<?php namespace Exolnet\Core;

class EnvironmentDetector
{
	private static $environments = [
		'development.exolnet.com' => 'local',
		'staging.exolnet.com'     => 'staging',
		'testing.exolnet.com'     => 'staging',
	];

	/**
	 * @param $environments
	 * @return callable
	 */
	public static function detect($environments)
	{
		// TODO: Do not allow $is_behat = true in production environment
		$is_behat = self::is_remote_test();
		if ($is_behat) {
			return function() { return 'test'; };
		}

		if (isset($_SERVER['HTTP_HOST']))
		{
			$host = $_SERVER['HTTP_HOST'];

			if (array_key_exists($host, self::$environments)) {
				return function() use ($host) { return self::$environments[$host]; };
			}
		}

		return $environments;
	}

	/**
	 * Add environements to host detector.
	 *
	 * @param array $environments
	 */
	public static function addEnvironments(array $environments)
	{
		static::$environments = $environments + static::$environments;
	}

	/**
	 * @return bool
	 */
	public static function is_remote_test()
	{
		return array_get($_COOKIE, 'test-env') === 'true';
	}
}

Update of the environment detect using hosts


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

namespace SecucardConnect\Product\Payment\Model;

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

    public $url_success;

    public $url_push;

    public $iframe_url;

}

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

namespace SecucardConnect\Product\Payment\Model;

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

    public $url_success;

    public $url_failure;

    public $iframe_url;

}

ADD some special uris for cc payment

ADD some special uris for cc payment


<?php

namespace ClientBundle\Validator\Constraints;

use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
use Doctrine\ORM\EntityRepository;
/**
 * Class ContainsCheckHaveAllContactTypesValidator
 */
class ContainsCheckHaveAllContactTypesValidator extends ConstraintValidator
{
    protected $repository;

    /**
     * ContainsCheckHaveAllContactTypesValidator constructor.
     * @param EntityRepository $repository
     */
    public function __construct(EntityRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * @param mixed      $client
     * @param Constraint $constraint
     */
    public function validate($client, Constraint $constraint)
    {
        $clientContacts = $client->getContacts();

        $allContactsTypeId = [];
        if (!empty($this->repository)) {
            $allContactsTypeId = $this->repository->getAllIds();
        }

        $clientContactsTypeId = [];
        foreach ($clientContacts as $contact) {
            $clientContactsTypeId[] = $contact->getType()->getId();
        }

        $result = array_diff($allContactsTypeId, $clientContactsTypeId);
        if (!empty($result)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('%name%', $client->getFirstName())
                ->addViolation();
        }
    }
}

Add blank line after use

Add blank line after use


<?php

$manager = \OC::$server->getEncryptionManager();
$module = new \OCA\Encryption_Dummy\DummyModule();
$manager->registerEncryptionModule($module);

<?php

$manager = \OC::$server->getEncryptionManager();
$module = new \OCA\Encryption_Dummy\DummyModule();
$manager->registerEncryptionModule('OC_DUMMY_MODULE', 'Dummy Encryption Module', $module);

Fix dummy encryption module registration


<?php

namespace PeterColes\Countries;

class Maker
{
    protected $countries = null;

    public function lookup($locale = 'en', $flip = false)
    {
        $this->prep($locale);

        if ($flip) {
            return $this->countries->flip();
        }

        return $this->countries;
    }

    public function keyValue($locale = 'en', $key = 'key', $value = 'value')
    {
        $this->prep($locale);

        $key = $key ?: 'key';
        $value = $value ?: 'value';

        return $this->countries->transform(function($item, $index) use ($key, $value) {
            return (object) [ $key => $index, $value =>$item ];
        })->values();
    }

    protected function prep($locale)
    {
        if (!$this->countries) {
            $locale = $locale ?: 'en';
            $this->countries = collect(require realpath(__DIR__."/../data/$locale.php"));
        }
    }
}

<?php

namespace PeterColes\Countries;

class Maker
{
    public function lookup($locale = 'en', $flip = false)
    {
        $this->prep($locale);

        if ($flip) {
            return $this->countries->flip();
        }

        return $this->countries;
    }

    public function keyValue($locale = 'en', $key = 'key', $value = 'value')
    {
        $this->prep($locale);

        $key = $key ?: 'key';
        $value = $value ?: 'value';

        return $this->countries->transform(function($item, $index) use ($key, $value) {
            return (object) [ $key => $index, $value =>$item ];
        })->values();
    }

    protected function prep($locale)
    {
        $locale = $locale ?: 'en';
        $this->countries = collect(require realpath(__DIR__."/../data/$locale.php"));
    }
}

Return a fresh collection every time - leave caching to calling application. This allows lists to be called for different languages and avoids hard-to-reason-about issues if the application applies transformations to the returned collection.


<?php
namespace Bolt;

class Pager extends \ArrayObject
{
    public $for;

    public $count;

    public $totalpages;

    public $current;

    public $showing_from;

    public $showing_to;

    public $link;

    protected $app;

    public function __construct($array, Application $app)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = new static($value, $app);
            }
            $this->$key = $value;
        }

        $this->app = $app;
    }

    /**
     * Used for calling from template to build up right paginated URL link.
     *
     * @return string
     */
    public function makelink()
    {
        /*
         * If link set directly that forces using it rather than build
         */
        if ($this->link) {
            return $this->link;
        }

        $pageid = static::makeParameterId($this->for);
        $parameters = $this->app['request']->query->all();
        if (array_key_exists($pageid, $parameters)) {
            unset($parameters[$pageid]);
        } else {
            unset($parameters['page']);
        }
        array_walk(
            $parameters,
            function (&$item, $key) {
                $item = "$key=$item";
            }
        );
        $parameters[] = $pageid . '=';
        $link = '?' . implode('&', $parameters);

        return $link;
    }

    public static function makeParameterId($suffix)
    {
        $suffix = ($suffix !== '') ? '_' . $suffix : '';

        return 'page' . $suffix;
    }
}

<?php
namespace Bolt;

class Pager extends \ArrayObject
{
    public $for;

    public $count;

    public $totalpages;

    public $current;

    public $showing_from;

    public $showing_to;

    public $link;

    protected $app;

    public function __construct($array, Application $app)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = new static($value, $app);
            }
            $this->$key = $value;
        }

        $this->app = $app;
    }

    /**
     * Used for calling from template to build up right paginated URL link.
     *
     * @return string
     */
    public function makelink()
    {
        /*
         * If link set directly that forces using it rather than build
         */
        if ($this->link) {
            return $this->link;
        }

        $pageid = static::makeParameterId($this->for);
        $parameters = $this->app['request']->query->all();
        if (array_key_exists($pageid, $parameters)) {
            unset($parameters[$pageid]);
        } else {
            unset($parameters['page']);
        }

        $parameters[$pageid] = '';
        $link = '?' . http_build_query($parameters);

        return $link;
    }

    public static function makeParameterId($suffix)
    {
        $suffix = ($suffix !== '') ? '_' . $suffix : '';

        return 'page' . $suffix;
    }
}

Allow non-strings as query parameters with pager.


<?php
/**
 * The main template file
 *
 */

get_header(); ?>

Hello, world

This is the start of something.

<?php get_footer(); ?>

<?php
/**
 * The main template file
 *
 */

get_header(); ?>

					Katherine

					Anne

					Porter

				correspondence

Over 5,000 pages of digitized materials granting unprecedented access
					 to the ideas, attitudes, and experiences of a distinguished
					 20th century American writer.

				 Read More

<?php get_footer(); ?>

Add real landing page text

Add real landing page text


<?php

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

class EcontDispatching extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) {
            $table->unsignedInteger('settlement_id');
            $table->enum('direction', ['from', 'to'])->index('idx_direction');
            $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment');
            $table->unsignedInteger('office_code');

            $table->primary(['settlement_id', 'direction', 'shipment', 'office_code']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching');
    }
}

<?php

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

class EcontDispatching extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) {
            $table->unsignedInteger('settlement_id');
            $table->enum('direction', ['from', 'to'])->index('idx_direction');
            $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment');
            $table->unsignedInteger('office_code');

            $table->primary(['settlement_id', 'direction', 'shipment']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching');
    }
}

Change type to shipment in dispatching.

Change type to shipment in dispatching.


<?php

namespace Smartbox\Integration\FrameworkBundle\Tools\EventsDeferring;

use JMS\Serializer\Annotation as JMS;
use Smartbox\CoreBundle\Type\SerializableInterface;
use Smartbox\Integration\FrameworkBundle\Events\Event;
use Smartbox\Integration\FrameworkBundle\Core\Messages\Message;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class EventMessage.
 */
class EventMessage extends Message
{
    const HEADER_EVENT_NAME = 'event_name';

    /**
     * @Assert\Valid(traverse=true)
     * @JMS\Type("Smartbox\Integration\FrameworkBundle\Events\Event")
     * @JMS\Groups({"logs"})
     * @JMS\Expose
     *
     * @var Event
     */
    protected $body;

    /**
     * @return Event
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * @param SerializableInterface $event
     */
    public function setBody(SerializableInterface $event = null)
    {
        if (!$event instanceof Event) {
            throw new \InvalidArgumentException('Expected Event as parameter');
        }

        if ($event->getEventName()) {
            $this->addHeader(self::HEADER_EVENT_NAME, $event->getEventName());
        }

        $this->body = $event;
    }
}

<?php

namespace Smartbox\Integration\FrameworkBundle\Tools\EventsDeferring;

use JMS\Serializer\Annotation as JMS;
use Smartbox\CoreBundle\Type\SerializableInterface;
use Smartbox\Integration\FrameworkBundle\Events\Event;
use Smartbox\Integration\FrameworkBundle\Core\Messages\Message;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class EventMessage.
 */
class EventMessage extends Message
{
    const HEADER_EVENT_NAME = 'event_name';

    /**
     * @Assert\Valid()
     * @JMS\Type("Smartbox\Integration\FrameworkBundle\Events\Event")
     * @JMS\Groups({"logs"})
     * @JMS\Expose
     *
     * @var Event
     */
    protected $body;

    /**
     * @return Event
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * @param SerializableInterface $event
     */
    public function setBody(SerializableInterface $event = null)
    {
        if (!$event instanceof Event) {
            throw new \InvalidArgumentException('Expected Event as parameter');
        }

        if ($event->getEventName()) {
            $this->addHeader(self::HEADER_EVENT_NAME, $event->getEventName());
        }

        $this->body = $event;
    }
}

SF34: Remove assertion config (traverse is true by default)


<?php

require_once dirname(__FILE__).'/../config.inc.php';
require_once dirname(__FILE__).'/../src/PEAR2Web/Router.php';
require_once dirname(__FILE__).'/../src/PEAR2Web/License.php';
require_once dirname(__FILE__).'/../src/PEAR2Web/Menu.php';

$channel = new \PEAR2\Pyrus\ChannelFile(__DIR__ . '/channel.xml');

$options = $_GET + PEAR2Web\Router::getRoute($_SERVER['REQUEST_URI']);

$frontend = new PEAR2\SimpleChannelFrontend\Main($channel, $options);

$savant = new PEAR2\Templates\Savant\Main();
$savant->setClassToTemplateMapper(
    new PEAR2\SimpleChannelFrontend\TemplateMapper
);
$savant->setTemplatePath(
    array(
        __DIR__ . '/templates/default/html',
        __DIR__ . '/templates/pear2/html'
    )
);

switch($frontend->options['format']) {
case 'rss':
    $savant->addTemplatePath(
        __DIR__ . '/templates/default/' . $frontend->options['format']
    );
    break;
}

$savant->setEscape('htmlspecialchars');
$savant->addFilters(array($frontend, 'postRender'));
echo $savant->render($frontend);

<?php

require_once dirname(__FILE__).'/../config.inc.php';
require_once dirname(__FILE__).'/../src/PEAR2Web/Router.php';
require_once dirname(__FILE__).'/../src/PEAR2Web/License.php';
require_once dirname(__FILE__).'/../src/PEAR2Web/Menu.php';

// Set preferred state to devel, so pyrus can get info on all releases
\PEAR2\Pyrus\Config::current()->preferred_state = 'devel';

$channel = new \PEAR2\Pyrus\ChannelFile(__DIR__ . '/channel.xml');

$options = $_GET + PEAR2Web\Router::getRoute($_SERVER['REQUEST_URI']);

$frontend = new PEAR2\SimpleChannelFrontend\Main($channel, $options);

$savant = new PEAR2\Templates\Savant\Main();
$savant->setClassToTemplateMapper(
    new PEAR2\SimpleChannelFrontend\TemplateMapper
);
$savant->setTemplatePath(
    array(
        __DIR__ . '/templates/default/html',
        __DIR__ . '/templates/pear2/html'
    )
);

switch($frontend->options['format']) {
case 'rss':
    $savant->addTemplatePath(
        __DIR__ . '/templates/default/' . $frontend->options['format']
    );
    break;
}

$savant->setEscape('htmlspecialchars');
$savant->addFilters(array($frontend, 'postRender'));
echo $savant->render($frontend);

Set the preferred state so pyrus/simplechannelfrontend can browse all releases.


<?php
require_once __DIR__."/header.php";
require_once(__DIR__."/views/views.php");
?>

<!DOCTYPE html>

	<?php if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"]){makeHeader("Add a Video");}
	else{
		makeHeader("Home");
	}
	?>

		<?php makeNav();?>

			<?php if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"]){
				makeAddVideo();
				echo "

				";
				exit(0);
			}?>

What is PodTube?

PodTube means taking YouTube on the go and sharing your favorite videos with friends.

How Does This Work?

Sign up for an account to get started.

Enter any YouTube video URL or video ID in the textbox and click "Add Video To Feed" to put the
				video into the created podcast feed. Then subscribe to the feed URL shown on the "Add Video" page
				with any podcatcher.

Development

PodTube is being developed by Michael Dombrowski
				 and the source is available on my GitHub.
				 Documentation is online here.

Add basic homepage for unauthenticated users


<?php

require_once 'vendor/autoload.php';

use App\Analyzer;

foreach ([10, 100, 1000, 10000] as $amount) {
    $analyzer = new Analyzer($amount);
    $analyzer->analyzeAlgorithms();
}

<?php

require_once 'vendor/autoload.php';

use App\Analyzer;

foreach ([10, 100, 1000] as $amount) {
    $analyzer = new Analyzer($amount);
    $analyzer->analyzeAlgorithms();
}

Test a little less for faster results.

Test a little less for faster results.


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for partialRight Mimic library function.
 *
 * @since 0.1.0
 */
class PartialRightFuncTest extends PHPUnit_Framework_TestCase {
	/**
	 * @covers ::Mimic\Functional\partialRight
	 */
	public function testInvokeIf_InvokeTrue() {
		$callback = F\partialRight('\Mimic\Functional\invokeIf', new Fake\InvokeTrue);
		$this->assertTrue($callback('exists'));
		$this->assertEquals(array(1, 2, 3), $callback('with', array(1, 2, 3)));
	}

	/**
	 * @covers ::Mimic\Functional\partialRight
	 */
	public function testArrayMerge() {
		$expected = array(1, 2, 3, 4, 5, 6);
		$callback = F\partialRight('array_merge', array(1, 2, 3));
		$this->assertEquals($expected, $callback(4, 5, 6));
	}
}

<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for partialRight Mimic library function.
 *
 * @since 0.1.0
 */
class PartialRightFuncTest extends PHPUnit_Framework_TestCase {
	/**
	 * @covers ::Mimic\Functional\partialRight
	 */
	public function testInvokeIf_InvokeTrue() {
		$callback = F\partialRight('\Mimic\Functional\invokeIf', new Fake\InvokeTrue);
		$this->assertTrue($callback('exists'));
		$this->assertEquals(array(1, 2, 3), $callback('with', array(1, 2, 3)));
	}

	/**
	 * @covers ::Mimic\Functional\partialRight
	 */
	public function testArrayMerge() {
		$expected = array(1, 2, 3, 4, 5, 6);
		$callback = F\partialRight('array_merge', array(1, 2, 3));
		$this->assertEquals($expected, $callback(array(4, 5, 6)));
	}
}

Fix test: Array merge accepts only arrays.


<?php

namespace App\Http\Controllers;

use App\Http\Middleware\EventsMiddleware;
use Illuminate\Http\Request;

class BotController extends Controller
{
    /**
     * Ensures the app has been verified and the token is correct
     */
    function __construct()
    {
        $this->middleware(EventsMiddleware::class);
    }

    /**
     * Handles events received from Slack
     */
    public function receive()
    {

    }

    /**
     * Posts responses to Slack
     */
    public function respond()
    {

    }
}

<?php

namespace App\Http\Controllers;

use App\Http\Middleware\EventsMiddleware;
use Illuminate\Http\Request;

class BotController extends Controller
{
    /**
     * Ensures the app has been verified and the token is correct
     */
    function __construct()
    {
        $this->middleware(EventsMiddleware::class);
    }

    /**
     * Handles events received from Slack
     */
    public function receive()
    {

    }

    /**
     * Posts responses to Slack
     */
    public function respond()
    {

    }

    public function parseText($text)
    {
        $tokens=explode(' ', $text);
        if($tokens[0]=="@linxer") {
            if($tokens[1]=="add" || $tokens[1]=="save") {
                return array( 'type' => 'add',
                                      'link' => $tokens[2],
                                      'tags' => array_slice($tokens, 3));
             } else if ($tokens[1]=="find" || $tokens[1]=="search") {
                return array( 'type' => 'search'
                                      'query_terms' =>  array_slice($tokens, 2));
             }
        }
    }
}

Implement parseText function for bot

Implement parseText function for bot


<?php

namespace UView;

class View {
	protected $storage = [];
	protected $path;

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

	public function set( $var, $value ) {
		$this->storage[ $var ] = $value;
	}

	public function __toString() {
		ob_start();

		// "Trigger" a "-" error, so that we can check if the include
		// issued any error. Unfortunately error_clear_last() requires
		// PHP >= 7.
		@trigger_error('-');

		extract($this->storage);
		@include $this->path;
		$err = error_get_last();
		$output = ob_get_clean();

		if ($err['message'] != '-') {
			// Call error_log() as a last resort.
			error_log($err['message']);
		}

		return $output;
	}
}

class Registry {

	protected $path;

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

	public function get( $name ) {
		$path = $this->path . "/$name.php";
		if ( ! file_exists($path) ) {
			throw new \RuntimeException("No such view '$name' found in '$this->path'");
		}
		return new View($path);
	}
}

<?php

namespace UView;

class View {
	protected $storage = [];
	protected $path;

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

	public function set( $var, $value ) {
		$this->storage[ $var ] = $value;
	}

	public function __toString() {
		ob_start();

		// "Trigger" a "-" error, so that we can check if the include
		// issued any error. Unfortunately error_clear_last() requires
		// PHP >= 7.
		@trigger_error('-');

		extract($this->storage);
		@include $this->path;
		$err = error_get_last();
		$output = ob_get_clean();

		if ($err['message'] != '-') {
			// Call error_log() as a last resort.
			error_log($err['message']);
		}

		return $output;
	}
}

class Registry {

	protected $path;

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

	public function get( $name ) {
		$path = $this->path . DIRECTORY_SEPARATOR . "$name.php";
		if ( ! file_exists($path) ) {
			throw new \RuntimeException("No such view '$name' found in '$this->path'");
		}
		return new View($path);
	}
}

Use DIRECTORY_SEPARATOR instead of hard-coded '/'

We never know where this thing is going to be run on.


<?php

namespace PHPOrchestra\ModelBundle\EventListener;

use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs;
use PHPOrchestra\ModelBundle\Model\StatusInterface;
use PHPOrchestra\ModelBundle\Model\StatusableInterface;

/**
 * Class SavePublishedDocumentListener
 */
class SavePublishedDocumentListener
{
    /**
     * @param LifecycleEventArgs $eventArgs
     */
    public function preUpdate(LifecycleEventArgs $eventArgs)
    {
        $document = $eventArgs->getDocument();
        if ($document instanceof StatusableInterface) {
            $status = $document->getStatus();
            if (! empty($status)
                 && $status->isPublished()
                 && (! method_exists($document, 'isDeleted') || ! $document->isDeleted())) {
                     $documentManager = $eventArgs->getDocumentManager();
                     $documentManager->getUnitOfWork()->detach($document);
            }
        }
    }
}

<?php

namespace PHPOrchestra\ModelBundle\EventListener;

use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs;
use PHPOrchestra\ModelBundle\Model\StatusInterface;
use PHPOrchestra\ModelBundle\Model\StatusableInterface;

/**
 * Class SavePublishedDocumentListener
 */
class SavePublishedDocumentListener
{
    /**
     * @param LifecycleEventArgs $eventArgs
     */
    public function preUpdate(LifecycleEventArgs $eventArgs)
    {
        $document = $eventArgs->getDocument();
        if ($document instanceof StatusableInterface) {
            $status = $document->getStatus();
            if (! empty($status)
                 && $status->isPublished()
                 && (!method_exists($document, 'isDeleted') || ! $document->isDeleted())
            ) {
                     $documentManager = $eventArgs->getDocumentManager();
                     $documentManager->getUnitOfWork()->detach($document);
            }
        }
    }
}

Add read only functionnality on published node


<?php

namespace Oro\Bundle\LocaleBundle\Migrations\Schema\Data\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Intl\Intl;

use Oro\Bundle\LocaleBundle\Entity\Localization;

class LoadLocalizationData extends AbstractFixture implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $localeSettings = $this->container->get('oro_locale.settings');
        $localeCode = $localeSettings->getLocale();
        $title = Intl::getLocaleBundle()->getLocaleName($localeSettings->getLanguage(), $localeCode);

        $localization = new Localization();
        $localization->setName($title)
            ->setDefaultTitle($title)
            ->setLanguageCode($localeCode)
            ->setFormattingCode($localeCode);

        $manager->persist($localization);
        /** @var EntityManager $manager */
        $manager->flush($localization);

        $this->addReference('default_localization', $localization);
    }
}

<?php

namespace Oro\Bundle\LocaleBundle\Migrations\Schema\Data\ORM;

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

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Intl\Intl;

use Oro\Bundle\LocaleBundle\Entity\Localization;

class LoadLocalizationData extends AbstractFixture implements ContainerAwareInterface
{
    /** @var ContainerInterface */
    protected $container;

    /**
     * {@inheritdoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $localeSettings = $this->container->get('oro_locale.settings');
        $localeCode = $localeSettings->getLocale();
        $title = Intl::getLocaleBundle()->getLocaleName($localeSettings->getLanguage(), $localeCode);

        $localization = new Localization();
        $localization->setName($title)
            ->setDefaultTitle($title)
            ->setLanguageCode($localeCode)
            ->setFormattingCode($localeCode);

        $manager->persist($localization);
        $manager->flush();

        $this->addReference('default_localization', $localization);
    }
}

BAP-10639: Update fixture for default locales
 - CR fixes


<?php
namespace TheNetworg\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class AzureResourceOwner implements ResourceOwnerInterface
{
    protected $response;

    public function __construct($response = []) {
        $this->response = $response;
    }

    public function getId() {
        return $this->response['objectId'] ?: null;
    }
}

<?php

namespace TheNetworg\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class AzureResourceOwner implements ResourceOwnerInterface
{
    /**
     * Response payload
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new azure resource owner.
     *
     * @param array  $response
     */
    public function __construct($response = [])
    {
        $this->response = $response;
    }

    /**
     * Retrieves id of azure resource owner.
     *
     * @return string|null
     */
    public function getId()
    {
        return $this->response['objectId'] ?: null;
    }
}

Add phpdocs and psr2 compliance to resource owner


<?php

declare(strict_types=1);

/*
 * (c) Christian Gripp <mail@core23.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Core23\DompdfBundle\DependencyInjection;

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

final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('core23_dompdf');

        /* @var ArrayNodeDefinition $rootNode */
        // Keep compatibility with symfony/config < 4.2
        if (!\method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->root('core23_dompdf');
        } else {
            $rootNode = $treeBuilder->getRootNode();
        }

        $rootNode
            ->children()
                ->arrayNode('defaults')
                    ->useAttributeAsKey('name')
                    ->prototype('scalar')->end()
                    ->defaultValue([
                        'fontCache' => '%kernel.cache_dir%',
                    ])
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

declare(strict_types=1);

/*
 * (c) Christian Gripp <mail@core23.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Core23\DompdfBundle\DependencyInjection;

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

final class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('core23_dompdf');

        // Keep compatibility with symfony/config < 4.2
        if (!\method_exists($treeBuilder, 'getRootNode')) {
            $rootNode = $treeBuilder->root('core23_dompdf');
        } else {
            $rootNode = $treeBuilder->getRootNode();
        }
        \assert($rootNode instanceof ArrayNodeDefinition);

        $rootNode
            ->children()
                ->arrayNode('defaults')
                    ->useAttributeAsKey('name')
                    ->prototype('scalar')->end()
                    ->defaultValue([
                        'fontCache' => '%kernel.cache_dir%',
                    ])
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Use asserts for type safe root config nodes


<?php

namespace Keyteq\Keymedia\API;

use Keyteq\Keymedia\API\Configuration;
use Keyteq\Keymedia\Util\RequestSigner;
use Keyteq\Keymedia\Util\RequestWrapper;

class RestConnector
{
    protected $config;
    protected $signer;
    protected $wrapper;

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

    public function getResource($resourceName, $resourceId, $parameters = array())
    {
        $path = "{$resourceName}/{$resourceId}.json";
        $url = $this->buildUrl($path, $parameters);
        $request = new Request($this->config, $this->signer, $this->wrapper);
        $request->setMethod('GET')->setUrl($url);

        return $request->perform();
    }

    public function getCollection($resourceName, $parameters = array())
    {
        $path = "{$resourceName}.json";
        $url = $this->buildUrl($path, $parameters);

        $request = new Request($this->config, new RequestSigner(), new RequestWrapper());
        $request->setMethod('GET')->setUrl($url);

        return $request->perform();
    }

    protected function buildUrl($path = '', $parameters = array())
    {
        $rootUrl = $this->config->getApiUrl();
        $url = "{$rootUrl}/{$path}";

        if (!empty($parameters)) {
            $url .= '?';
            foreach ($parameters as $k => $v) {
                $url .= $k . '=' . $v;
            }
        }

        return $url;
    }
}

<?php

namespace Keyteq\Keymedia\API;

use Keyteq\Keymedia\API\Configuration;
use Keyteq\Keymedia\Util\RequestSigner;
use Keyteq\Keymedia\Util\RequestWrapper;

class RestConnector
{
    protected $config;
    protected $signer;
    protected $wrapper;

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

    public function getResource($resourceName, $resourceId, $parameters = array())
    {
        $path = "{$resourceName}/{$resourceId}.json";
        $url = $this->buildUrl($path, $parameters);
        $request = new Request($this->config, $this->signer, $this->wrapper);
        $request->setMethod('GET')->setUrl($url);

        return $request->perform();
    }

    public function getCollection($resourceName, $parameters = array())
    {
        $path = "{$resourceName}.json";
        $url = $this->buildUrl($path, $parameters);

        $request = new Request($this->config, new RequestSigner(), new RequestWrapper());
        $request->setMethod('GET')->setUrl($url);

        return $request->perform();
    }

    protected function buildUrl($path = '', $parameters = array())
    {
        $rootUrl = $this->config->getApiUrl();
        $url = "{$rootUrl}/{$path}";

        if (!empty($parameters)) {
            $url .= '?' . http_build_query($parameters);
        }

        return $url;
    }
}

Fix building queries with more than one parameter


<?php
namespace Phragile;

class StatusDispatcherFactory {
	private $workboardMode = false;

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

	/**
	 * @return StatusDispatcher
	 */
	public function createInstance()
	{
		if ($this->workboardMode) return new StatusByWorkboardDispatcher();
		else return new StatusByStatusFieldDispatcher();
	}
}

<?php
namespace Phragile;

class StatusDispatcherFactory {
	private $workboardMode = false;

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

	/**
	 * @return StatusDispatcher
	 */
	public function createInstance()
	{
		return $this->workboardMode
			? new StatusByWorkboardDispatcher()
			: new StatusByStatusFieldDispatcher();
	}
}

Use ternary instead of if-statement.

Use ternary instead of if-statement.


<?php

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfiguration;
use CdliTwoStageSignupTest\Framework\TestCase;

chdir(__DIR__);

$previousDir = '.';
while (!file_exists('config/application.config.php')) {
    $dir = dirname(getcwd());
    if($previousDir === $dir) {
        throw new RuntimeException(
            'Unable to locate "config/application.config.php":'
            . ' is CdliTwoStageSignup in a subdir of your application skeleton?'
        );
    }
    $previousDir = $dir;
    chdir($dir);
}

if (!include('vendor/autoload.php')) {
    throw new RuntimeException(
        'vendor/autoload.php could not be found. '
        . 'Did you run php composer.phar install in your application skeleton?'
    );
}

// Get application stack configuration
$configuration = include 'config/application.config.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager']));
$serviceManager->setService('ApplicationConfiguration', $configuration);
$config = $serviceManager->get('Configuration');

TestCase::setServiceLocator($serviceManager);

<?php

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfiguration;
use CdliTwoStageSignupTest\Framework\TestCase;

chdir(__DIR__);

$previousDir = '.';
while (!file_exists('config/application.config.php')) {
    $dir = dirname(getcwd());
    if($previousDir === $dir) {
        throw new RuntimeException(
            'Unable to locate "config/application.config.php":'
            . ' is CdliTwoStageSignup in a subdir of your application skeleton?'
        );
    }
    $previousDir = $dir;
    chdir($dir);
}

if (!include('vendor/autoload.php')) {
    throw new RuntimeException(
        'vendor/autoload.php could not be found. '
        . 'Did you run php composer.phar install in your application skeleton?'
    );
}

// Get application stack configuration
$configuration = include 'config/application.config.php';
$configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php';

// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager']));
$serviceManager->setService('ApplicationConfiguration', $configuration);
$config = $serviceManager->get('Configuration');

TestCase::setServiceLocator($serviceManager);

Add glob for test-specific configuration files


<?php

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

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

require __DIR__.'/PHPUnit/ArrayHasSameValuesConstraint.php';
require __DIR__.'/PHPUnit/RedisCommandConstraint.php';
require __DIR__.'/PHPUnit/PredisTestCase.php';
require __DIR__.'/PHPUnit/PredisCommandTestCase.php';
require __DIR__.'/PHPUnit/PredisConnectionTestCase.php';
require __DIR__.'/PHPUnit/PredisProfileTestCase.php';
require __DIR__.'/PHPUnit/PredisDistributorTestCase.php';

<?php

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

if (file_exists(__DIR__.'/../autoload.php')) {
    require __DIR__.'/../autoload.php';
} else if (@include('Predis/Autoloader.php')) {
    Predis\Autoloader::register();
} else {
    die('ERROR: Unable to find a suitable mean to register Predis\Autoloader.');
}

require __DIR__.'/PHPUnit/ArrayHasSameValuesConstraint.php';
require __DIR__.'/PHPUnit/RedisCommandConstraint.php';
require __DIR__.'/PHPUnit/PredisTestCase.php';
require __DIR__.'/PHPUnit/PredisCommandTestCase.php';
require __DIR__.'/PHPUnit/PredisConnectionTestCase.php';
require __DIR__.'/PHPUnit/PredisProfileTestCase.php';
require __DIR__.'/PHPUnit/PredisDistributorTestCase.php';

[tests] Use Predis\Autoload from include_path when not in repository.

This is useful only for running the test suite after installing the
PEAR package, see #126 for reference.


<?php

namespace PhpAbac\Comparison;

class ArrayComparison
{
    /**
     * @param array $haystack
     * @param mixed  $needle
     *
     * @return bool
     */
    public function isIn($haystack, $needle)
    {
        return in_array($needle, $haystack);
    }

    /**
     * @param array $haystack
     * @param mixed  $needle
     *
     * @return bool
     */
    public function isNotIn($haystack, $needle)
    {
        return !$this->isIn($haystack, $needle);
    }

    /**
     * @param array $array1
     * @param array $array2
     *
     * @return bool
     */
    public function intersect($array1, $array2)
    {
        return count(array_intersect($array1, $array2)) > 0;
    }

    /**
     * @param array $array1
     * @param array $array2
     *
     * @return bool
     */
    public function doNotIntersect($array1, $array2)
    {
        return !$this->intersect($array1, $array2);
    }
}

<?php

namespace PhpAbac\Comparison;

class ArrayComparison extends AbstractComparison
{
    /**
     * @param array $haystack
     * @param mixed  $needle
     *
     * @return bool
     */
    public function isIn($haystack, $needle)
    {
        return in_array($needle, $haystack);
    }

    /**
     * @param array $haystack
     * @param mixed  $needle
     *
     * @return bool
     */
    public function isNotIn($haystack, $needle)
    {
        return !$this->isIn($haystack, $needle);
    }

    /**
     * @param array $array1
     * @param array $array2
     *
     * @return bool
     */
    public function intersect($array1, $array2)
    {
        return count(array_intersect($array1, $array2)) > 0;
    }

    /**
     * @param array $array1
     * @param array $array2
     *
     * @return bool
     */
    public function doNotIntersect($array1, $array2)
    {
        return !$this->intersect($array1, $array2);
    }

    /**
     * @param array $policyRuleAttributes
     * @param array $attributes
     * @return boolean
     */
    public function contains($policyRuleAttributes, $attributes, $extraData = []) {
        foreach($extraData['attribute']->getValue() as $attribute) {
            $result = true;
            foreach($policyRuleAttributes as $pra) {
                $attributeData = $pra->getAttribute();
                if(!$this->comparisonManager->compare(
                    $pra->getComparisonType(),
                    $pra->getComparison(),
                    $pra->getValue(),
                    $this->comparisonManager->getAttributeManager()->retrieveAttribute($attributeData, $extraData['user'], $attribute)
                )) {
                    $result = false;
                    break;
                }
            }
            if($result === true) {
                return true;
            }
        }
        return false;
    }
}

Implement a new comparison for arrays

Implement a new comparison for arrays


<?php

use Estaty\Application;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;
// use Silex\Provider\ValidatorServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;

// Use Composer autoloader
require_once __DIR__.'/../vendor/autoload.php';

$app = new Application();

$app->register(new UrlGeneratorServiceProvider());
// $app->register(new ValidatorServiceProvider());
$app->register(new ServiceControllerServiceProvider());
$app->register(new TwigServiceProvider());

// include the default configuration
require __DIR__.'/../config/default.php';

// Load environment and relevant configuration
$environment = getenv('ESTATY_ENV') ?: 'prod';
require __DIR__.'/../config/'.$environment.'.php';
unset($environment);

// http://silex.sensiolabs.org/doc/cookbook/error_handler.html
ErrorHandler::register();
ExceptionHandler::register($app['debug']);

return $app;

<?php

use Estaty\Application;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\UrlGeneratorServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;

// Use Composer autoloader
require_once __DIR__.'/../vendor/autoload.php';

$app = new Application();

$app->register(new UrlGeneratorServiceProvider());
$app->register(new ServiceControllerServiceProvider());
$app->register(new TwigServiceProvider());

// include the default configuration
require __DIR__.'/../config/default.php';

// Load environment and relevant configuration
$environment = getenv('ESTATY_ENV') ?: 'prod';
require __DIR__.'/../config/'.$environment.'.php';
unset($environment);

// http://silex.sensiolabs.org/doc/cookbook/error_handler.html
ErrorHandler::register();
ExceptionHandler::register($app['debug']);

return $app;

Remove commented ValidatorServiceProvider for now


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Orchestra\Story\Model\Content;

class OrchestraStoryMakeContentsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		$format = Config::get('orchestra/story::default_format', 'markdown');

		Schema::create('story_contents', function ($table) use ($format)
		{
			$table->increments('id');
			$table->integer('user_id')->unsigned();
			$table->string('slug');
			$table->string('title');
			$table->text('content');
			$table->string('format')->default($format);
			$table->string('type')->default(Content::POST);
			$table->string('status')->default(Content::STATUS_DRAFT);

			$table->timestamps();
			$table->datetime('published_at');
			$table->softDeletes();

			$table->index('user_id');
			$table->index('slug');
			$table->index('format');
		});
	}

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

}

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Orchestra\Story\Model\Content;

class OrchestraStoryMakeContentsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		$format = Config::get('orchestra/story::config.default_format', 'markdown');

		Schema::create('story_contents', function ($table) use ($format)
		{
			$table->increments('id');
			$table->integer('user_id')->unsigned();
			$table->string('slug');
			$table->string('title');
			$table->text('content');
			$table->string('format')->default($format);
			$table->string('type')->default(Content::POST);
			$table->string('status')->default(Content::STATUS_DRAFT);

			$table->timestamps();
			$table->datetime('published_at');
			$table->softDeletes();

			$table->index('user_id');
			$table->index('slug');
			$table->index('format');
		});
	}

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

}

Revert changes, doesn't seem to work.

Revert changes, doesn't seem to work.

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


<?php

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

/**
 * Authentication
 *
 * You'll get the client id and secret at the plaform (API Access)
 **/
$Client = new Productsup\Client();
$Client->id = 1234;
$Client->secret = 'simsalabim';

$ProductData = new Productsup\Service\ProductData($Client);

/**
 * Optional, define chunk site to submit products in parts using multiple
 * post requests. Default is 5000
 */
$ProductData->setPostLimit(1000);

$Reference = new Productsup\Platform\Site\Reference();

/**
 * In case you have a productsup site id
 **/
$Reference->setKey($Reference::REFERENCE_SITE);
$Reference->setValue(1234); // Site ID

/**
 * In case you have a metadata tag as reference
 **/
$Reference->setKey('merchant_id'); // A site tag
$Reference->setValue(1234); // Value of the tag

$ProductData->setReference($Reference);

/**
 * Add Products to insert
 */
$ProductData->insert(array('id' => '123'));
$ProductData->insert(array('id' => '124'));

/**
 * Commit all inserts
 */
$result = $ProductData->commit();

var_dump($result);

<?php

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

/**
 * Authentication
 *
 * You'll get the client id and secret at the plaform (API Access)
 **/
$Client = new Productsup\Client();
$Client->id = 1234;
$Client->secret = 'simsalabim';

$ProductData = new Productsup\Service\ProductData($Client);

/**
 * Optional, define chunk site to submit products in parts using multiple
 * post requests. Default is 5000
 */
$ProductData->setPostLimit(1000);

$Reference = new Productsup\Platform\Site\Reference();

/**
 * In case you have a productsup site id
 **/
$Reference->setKey($Reference::REFERENCE_SITE);
$Reference->setValue(1234); // Site ID

/**
 * In case you want to use your own reference
 **/
$Reference->setKey('merchant_id'); // A site tag
$Reference->setValue(1234); // Value of the tag

$ProductData->setReference($Reference);

/**
 * Add Products to insert
 */
$ProductData->insert(array('id' => '123'));
$ProductData->insert(array('id' => '124'));

/**
 * Commit all inserts
 */
$result = $ProductData->commit();

var_dump($result);

Use Reference instead Site for Tags

Use Reference instead Site for Tags


Hey {{ $user->username }}!

{{ $blueprint->post->user->username }} made a post in a discussion you're following: {{ $blueprint->post->discussion->title }}

To view the new activity, check out the following link:
{{ \Flarum\Core::config('base_url') }}/d/{{ $blueprint->post->discussion_id }}/{{ $blueprint->post->number }}

---

{{ strip_tags($blueprint->post->contentHtml) }}

---

You won't receive any more notifications about this discussion until you're up-to-date.

Hey {{ $user->username }}!

{{ $blueprint->post->user->username }} made a post in a discussion you're following: {{ $blueprint->post->discussion->title }}

To view the new activity, check out the following link:
{{ \Flarum\Core::url() }}/d/{{ $blueprint->post->discussion_id }}/{{ $blueprint->post->number }}

---

{{ strip_tags($blueprint->post->contentHtml) }}

---

You won't receive any more notifications about this discussion until you're up-to-date.

Use new method for retrieving base URL

Use new method for retrieving base URL


<?php

declare(strict_types=1);

namespace Stratadox\Di;

use ReflectionClass;

final class AutoWiring
{
    private $container;

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

    public static function the(ContainerInterface $container) : self
    {
        return new self($container, []);
    }

    public function get(string $service)
    {
        if (!$this->container->has($service)) {
            $this->resolve($service);
        }
        return $this->container->get($service);
    }

    private function resolve(string $service)
    {
        $constructor = (new ReflectionClass($service))->getConstructor();
        $dependencies = [];
        if (isset($constructor)) {
            foreach ($constructor->getParameters() as $parameter) {
                $dependency = (string) $parameter->getType();
                $this->resolve($dependency);
                $dependencies[] = $dependency;
            }
        }
        $this->container->set($service,
            function () use ($service, $dependencies) {
                $parameters = [];
                foreach ($dependencies as $dependency) {
                    $parameters[] = $this->container->get($dependency);
                }
                return new $service(...$parameters);
            }
        );
    }
}

<?php

declare(strict_types=1);

namespace Stratadox\Di;

use ReflectionClass;

final class AutoWiring
{
    private $container;
    private $links;

    private function __construct(ContainerInterface $container, array $links)
    {
        $this->container = $container;
        $this->links = $links;
    }

    public static function the(ContainerInterface $container) : self
    {
        return new self($container, []);
    }

    public function link(string $interface, string $class) : self
    {
        return new self($this->container, [$interface => $class]);
    }

    public function get(string $service)
    {
        if (!$this->container->has($service)) {
            $this->resolve($service);
        }
        return $this->container->get($service);
    }

    private function resolve(string $service)
    {
        if (interface_exists($service)) {
            $this->resolveInterface($service);
        } else {
            $this->resolveClass($service);
        }
    }

    private function resolveInterface(string $service)
    {
        $class = $this->links[$service];
        $this->resolveClass($class);
        $this->container->set($service, function () use ($class) {
            return $this->container->get($class);
        });
    }

    private function resolveClass(string $service)
    {
        $constructor = (new ReflectionClass($service))->getConstructor();
        $dependencies = [];
        if (isset($constructor)) {
            foreach ($constructor->getParameters() as $parameter) {
                $dependency = (string) $parameter->getType();
                $this->resolve($dependency);
                $dependencies[] = $dependency;
            }
        }
        $this->container->set($service,
            function () use ($service, $dependencies) {
                $parameters = [];
                foreach ($dependencies as $dependency) {
                    $parameters[] = $this->container->get($dependency);
                }
                return new $service(...$parameters);
            }
        );
    }
}

Add support for interface typehints

Add support for interface typehints


<?php

if (!empty($GLOBALS['Session']) && $GLOBALS['Session']->hasAccountLevel('Staff')) {
    Slate\UI\Tools::$tools['Student Progress'] = [
        'Narrative Reports' => [
            '_href' => '/manage#progress/narratives',
            '_icon' => 'documents'
        ]
    ];
}

<?php

if (empty($GLOBALS['Session']) || !$GLOBALS['Session']->hasAccountLevel('Staff')) {
    return;
}

Slate\UI\Tools::$tools['Student Progress']['Interim Reports'] = [
    '_href' => '/manage#progress/interims/report',
    '_icon' => 'interims'
];

Slate\UI\Tools::$tools['Student Progress']['Term Reports'] = [
    '_href' => '/manage#progress/terms/report',
    '_icon' => 'documents'
];

Update tool links for interim and term reports


<?php

use Pecee\SimpleRouter\SimpleRouter as Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;

Route::group(['prefix' => '/api'], function() {
    Route::get('/secret', function() {
        return 'API Secret';
    });

    Route::post('/login', 'AuthController@login');
    Route::post('/register', 'AuthController@register');
    Route::post('logout', 'AuthController@logout');
});

Route::error(function(Request $request, \Exception $exception) {
    if($exception instanceof NotFoundHttpException && $exception->getCode() === 404) {
        response()->redirect('/api/secret');
    }
});

<?php

use Pecee\SimpleRouter\SimpleRouter as Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;

Route::group(['prefix' => '/api'], function() {
    Route::get('/secret', function() {
        return 'API Secret';
    });

    Route::post('login', 'AuthController@login');
    Route::post('register', 'AuthController@register');
    Route::post('logout', 'AuthController@logout');
});

Route::error(function(Request $request, \Exception $exception) {
    if($exception instanceof NotFoundHttpException && $exception->getCode() === 404) {
        response()->redirect('/api/secret');
    }
});

Standardize route in php by removing leading slash


<?php

namespace Jmikola\ImagineBundle\Imagine\Filter;

use Imagine\Exception\InvalidArgumentException;

use Imagine\Filter\FilterInterface;
use Imagine\Image\ImageInterface;
use Imagine\Image\BoxInterface;

class RelativeResize implements FilterInterface
{
    private $method;
    private $parameter;

    /**
     * Constructs a RelativeResize filter with the given method and argument.
     *
     * @param string $method    BoxInterface method
     * @param mixed  $parameter Parameter for BoxInterface method
     */
    public function __construct($method, $parameter)
    {
        if (!in_array($method, array('heighten', 'increase', 'scale', 'widen'))) {
            throw new InvalidArgumentException(sprintf('Unsupported method: ', $method));
        }

        $this->method = $method;
        $this->parameter = $parameter;
    }

    /**
     * @see Imagine\Filter\FilterInterface::apply()
     */
    public function apply(ImageInterface $image)
    {
        return $image->resize(call_user_func(array($image->getSize(), $this->method), $this->parameter));
    }
}

Remove whitespace between use statements


<?php
class Kwc_Basic_LinkTag_Intern_Form extends Kwc_Abstract_Form
{
    public function __construct($name, $class, $id = null)
    {
        parent::__construct($name, $class, $id);

        $this->add(new Kwf_Form_Field_PageSelect('target', trlKwf('Target')))
            ->setControllerUrl(Kwc_Admin::getInstance($class)->getControllerUrl('Pages'))
            ->setWidth(233)
            ->setAllowBlank(false);

        $this->add(new Kwf_Form_Field_Select('anchor', trlKwf('Anchor')))
            ->setValues(Kwc_Admin::getInstance($class)->getControllerUrl('Anchors') . '/json-data')
            ->setShowNoSelection(true);
    }

    public function prepareSave($parentRow, $postData)
    {
        if ($parentRow) {
            // Limit 1 weil alle komponenten die hier zurück kommen, dieselbe url
            // haben und es wird ja überprüft ob zu sich selbst gelinkt wird
            $data = Kwf_Component_Data_Root::getInstance()->getComponentByDbId(
                $parentRow->component_id, array('limit' => 1)
            );
            if (isset($postData[$this->fields['target']->getFieldName()]) &&
                    $data && $data->getPage() && $data->getPage()->dbId == $postData[$this->fields['target']->getFieldName()]) {
                throw new Kwf_ClientException(trlKwf('Link cannot link to itself'));
            }
        }
        parent::prepareSave($parentRow, $postData);
    }
}

<?php
class Kwc_Basic_LinkTag_Intern_Form extends Kwc_Abstract_Form
{
    public function __construct($name, $class, $id = null)
    {
        parent::__construct($name, $class, $id);

        $this->add(new Kwf_Form_Field_PageSelect('target', trlKwf('Target')))
            ->setControllerUrl(Kwc_Admin::getInstance($class)->getControllerUrl('Pages'))
            ->setWidth(233)
            ->setAllowBlank(false);

        $this->add(new Kwf_Form_Field_Select('anchor', trlKwf('Anchor')))
            ->setValues(Kwc_Admin::getInstance($class)->getControllerUrl('Anchors') . '/json-data')
            ->setShowNoSelection(true);
    }

    public function prepareSave($parentRow, $postData)
    {
        if ($parentRow) {
            // Limit 1 weil alle komponenten die hier zurück kommen, dieselbe url
            // haben und es wird ja überprüft ob zu sich selbst gelinkt wird
            $data = Kwf_Component_Data_Root::getInstance()->getComponentByDbId(
                $parentRow->component_id, array('limit' => 1, 'ignoreVisible' => true)
            );
            if (isset($postData[$this->fields['target']->getFieldName()]) &&
                $data && $data->isPage && $data->getPage() &&
                $data->getPage()->dbId == $postData[$this->fields['target']->getFieldName()]
            ) {
                throw new Kwf_ClientException(trlKwf('Link cannot link to itself'));
            }
        }
        parent::prepareSave($parentRow, $postData);
    }
}

Allow linking to own page when link is in content


<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class AssetCheckoutRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            "assigned_user"   => 'required_without_all:assigned_asset,assigned_location',
            "assigned_asset"   => 'required_without_all:assigned_user,assigned_location|different:'.$this->id,
            "assigned_location"   => 'required_without_all:assigned_user,assigned_asset',
        ];

        return $rules;
    }
}

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class AssetCheckoutRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            "assigned_user"         => 'required_without_all:assigned_asset,assigned_location',
            "assigned_asset"        => 'required_without_all:assigned_user,assigned_location|different:'.$this->id,
            "assigned_location"     => 'required_without_all:assigned_user,assigned_asset',
            "checkout_to_type"      => 'required|in:asset,location,user'
        ];

        return $rules;
    }
}

Validate checkout_to_type on asset checkout


<?php
/**
 * Global Configuration Override
 *
 * You can use this file for overriding configuration values from modules, etc.
 * You would place values in here that are agnostic to the environment and not
 * sensitive to security.
 *
 * @NOTE: In practice, this file will typically be INCLUDED in your source
 * control, so do not include passwords or other sensitive information in this
 * file.
 */

return array(
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
    ),
);

<?php
/**
 * Global Configuration Override
 *
 * You can use this file for overriding configuration values from modules, etc.
 * You would place values in here that are agnostic to the environment and not
 * sensitive to security.
 *
 * @NOTE: In practice, this file will typically be INCLUDED in your source
 * control, so do not include passwords or other sensitive information in this
 * file.
 */

return array(
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
        'abstract_factories' => array(
           'Zend\Db\Adapter\AdapterAbstractServiceFactory',
        ),
    ),
);

Add Zend\Db\Adapter\AdapterAbstractServiceFactory to the service manager


<?php
/**
 * @package plugins.metadata
 * @subpackage model
 */
class MetadataDynamicObjectPeer extends MetadataPeer implements IMetadataPeer
{
    public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage)
    {
        /** @var MetadataProfileField $profileField */
	    $subMetadataProfileId = $profileField->getRelatedMetadataProfileId();
        $subMetadataProfile = MetadataProfilePeer::retrieveByPK($subMetadataProfileId);
		if (!$subMetadataProfile)
		{
		    $errorMessage = 'Sub metadata profile ' . $subMetadataProfileId . ' was not found';
            return false;
		}

		$subMetadataObjects = MetadataPeer::retrieveByObjects($subMetadataProfileId, $subMetadataProfile->getObjectType(), $objectIds);
		if (count($subMetadataObjects) != count($objectIds))
		{
		    $errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found for profile '.$subMetadataProfileId;
			return false;
		}

		return true;
    }

	public static function getEntry($objectId)
	{
		return null;
	}

	public static function validateMetadataObjectAccess(metadata $dbMetadata)
	{
		return true;
	}
}

<?php
/**
 * @package plugins.metadata
 * @subpackage model
 */
class MetadataDynamicObjectPeer extends MetadataPeer implements IMetadataPeer
{
    public static function validateMetadataObjects($profileField, $objectIds, &$errorMessage)
    {
        /** @var MetadataProfileField $profileField */
	    $subMetadataProfileId = $profileField->getRelatedMetadataProfileId();
        $subMetadataProfile = MetadataProfilePeer::retrieveByPK($subMetadataProfileId);
		if (!$subMetadataProfile)
		{
		    $errorMessage = 'Sub metadata profile ' . $subMetadataProfileId . ' was not found';
            return false;
		}

		$subMetadataObjects = MetadataPeer::retrieveByObjects($subMetadataProfileId, $subMetadataProfile->getObjectType(), $objectIds);
		if (count($subMetadataObjects) != count($objectIds))
		{
		    $errorMessage = 'One of the following objects: '.implode(', ', $objectIds).' was not found for profile '.$subMetadataProfileId;
			return false;
		}

		return true;
    }

	public static function getEntry($objectId)
	{
		return null;
	}

	public static function validateMetadataObjectAccess($objectId, $objectType)
	{
		return true;
	}
}

Fix function signature to match base one


<?php

namespace PHPSW\Command\Redis;

use Knp\Command\Command,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface,
    Symfony\Component\Finder\Finder;

class RestoreCommand extends Command
{
    protected function configure()
    {
        $this->setName('redis:restore-fixtures');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $app = $this->getSilexApplication();

        $fixtures = $app['console.project_directory'] . '/fixtures';
        $redis = $app['redis'];

        foreach (Finder::create()->depth(0)->in($fixtures) as $node) {
            $hash = $node->getFilename();

            echo $hash . ': ';

            if ($node->isDir()) {
                foreach (Finder::create()->files()->in($node->getPathname()) as $file) {
                    $key = $file->getFilename();

                    $redis->hset($hash, $key, $this->parse($file->getContents()));

                    echo '.';
                }
            } else {
                $redis->set($hash, $this->parse($node->getContents()));

                echo '.';
            }

            echo PHP_EOL;
        }
    }

    protected function parse($value)
    {
        if (preg_match('#^\{|\[.*\]|\}$#', $value)) {
            $value = json_encode(json_decode($value));
        }

        return $value;
    }
}

<?php

namespace PHPSW\Command\Redis;

use Knp\Command\Command,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface,
    Symfony\Component\Finder\Finder;

class RestoreCommand extends Command
{
    protected function configure()
    {
        $this->setName('redis:restore-fixtures');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $app = $this->getSilexApplication();

        $fixtures = $app['console.project_directory'] . '/fixtures';
        $redis = $app['redis'];

        foreach (Finder::create()->depth(0)->in($fixtures) as $node) {
            $hash = $node->getFilename();

            echo $hash . ': ';

            if ($node->isDir()) {
                foreach (Finder::create()->files()->in($node->getPathname())->sortByName() as $file) {
                    $key = $file->getFilename();

                    $redis->hset($hash, $key, $this->parse($file->getContents()));

                    echo '.';
                }
            } else {
                $redis->set($hash, $this->parse($node->getContents()));

                echo '.';
            }

            echo PHP_EOL;
        }
    }

    protected function parse($value)
    {
        if (preg_match('#^\{|\[.*\]|\}$#', $value)) {
            $value = json_encode(json_decode($value));
        }

        return $value;
    }
}

Sort redis restore so that output is consistent


<?php namespace Bosnadev\Database\Connectors;

use PDO;
use Illuminate\Database\MySqlConnection;
use Illuminate\Database\SQLiteConnection;
use Illuminate\Database\SqlServerConnection;
use Bosnadev\Database\PostgresConnection;

/**
 * Class ConnectionFactory
 * @package Bosnadev\Database\Connectors
 */
class ConnectionFactory extends \Illuminate\Database\Connectors\ConnectionFactory
{
    /**
     * @param string $driver
     * @param PDO $connection
     * @param string $database
     * @param string $prefix
     * @param array $config
     * @return PostgresConnection|MySqlConnection|SQLiteConnection|SqlServerConnection|mixed|object
     * @throws \InvalidArgumentException
     */
    protected function createConnection($driver, PDO $connection, $database, $prefix = '', array $config = array())
    {
        if ($this->container->bound($key = "db.connection.{$driver}")) {
            return $this->container->make($key, array($connection, $database, $prefix, $config));
        }

        if ($driver === 'pgsql') {
            return new PostgresConnection($connection, $database, $prefix, $config);
        }

        return parent::createConnection($driver, $connection, $database, $prefix, $config);
    }
}

<?php namespace Bosnadev\Database\Connectors;

use PDO;
use Illuminate\Database\MySqlConnection;
use Illuminate\Database\SQLiteConnection;
use Illuminate\Database\SqlServerConnection;
use Bosnadev\Database\PostgresConnection;

/**
 * Class ConnectionFactory
 * @package Bosnadev\Database\Connectors
 */
class ConnectionFactory extends \Illuminate\Database\Connectors\ConnectionFactory
{
    /**
     * @param string $driver
     * @param PDO $connection
     * @param string $database
     * @param string $prefix
     * @param array $config
     * @return PostgresConnection|MySqlConnection|SQLiteConnection|SqlServerConnection|mixed|object
     * @throws \InvalidArgumentException
     */
    protected function createConnection($driver, $connection, $database, $prefix = '', array $config = array())
    {
        if ($this->container->bound($key = "db.connection.{$driver}")) {
            return $this->container->make($key, array($connection, $database, $prefix, $config));
        }

        if ($driver === 'pgsql') {
            return new PostgresConnection($connection, $database, $prefix, $config);
        }

        return parent::createConnection($driver, $connection, $database, $prefix, $config);
    }
}

Update connection factory to have same signature as parent for php7 compatibility


<?php

namespace Oro\Bundle\EmailBundle\Sync\Model;

class SynchronizationProcessorSettings
{
    /** @var  bool In this mode all emails will be re-synced again for checked folders */
    protected $forceMode = false;

    /** @var bool Allows to define show or hide log messages during resync of emails */
    protected $showMessage = false;

    public function __construct($forceMode = false, $showMessage = false)
    {
        $this->forceMode = $forceMode;
        $this->showMessage = $showMessage;
    }

    /**
     * Set force mode.
     *
     * @param bool $mode
     */
    public function setForceMode($mode)
    {
        $this->forceMode = $mode;
    }

    /**
     * Check is force mode enabled.
     */
    public function isForceMode()
    {
        return $this->forceMode === true;
    }

    /**
     * Set value to show or hide log messages
     *
     * @param bool $value
     */
    public function setShowMessage($value)
    {
        $this->showMessage = $value;
    }

    /**
     * Check value is true.
     *
     * @return bool
     */
    public function needShowMessage()
    {
        return $this->showMessage === true;
    }
}

<?php

namespace Oro\Bundle\EmailBundle\Sync\Model;

class SynchronizationProcessorSettings
{
    /** @var  bool In this mode all emails will be re-synced again for checked folders */
    protected $forceMode = false;

    /** @var bool Allows to define show or hide log messages during resync of emails */
    protected $showMessage = false;

    /**
     * @param bool $forceMode
     * @param bool $showMessage
     */
    public function __construct($forceMode = false, $showMessage = false)
    {
        $this->forceMode = $forceMode;
        $this->showMessage = $showMessage;
    }

    /**
     * Set force mode.
     *
     * @param bool $mode
     */
    public function setForceMode($mode)
    {
        $this->forceMode = $mode;
    }

    /**
     * Check is force mode enabled.
     */
    public function isForceMode()
    {
        return $this->forceMode === true;
    }

    /**
     * Set value to show or hide log messages
     *
     * @param bool $value
     */
    public function setShowMessage($value)
    {
        $this->showMessage = $value;
    }

    /**
     * Check value is true.
     *
     * @return bool
     */
    public function needShowMessage()
    {
        return $this->showMessage === true;
    }
}

BAP-11558: Add force Resync parameter for IMAP synchronization command


<?php
/**
 * A background job which builds a single extension.
 */
class BuildExtensionJob {

	public function setUp() {
		global $databaseConfig;

		if (!DB::isActive()) {
			DB::connect($databaseConfig);
		}
	}

	public function perform() {
		Injector::inst()->get('ExtensionBuilder')->build(ExtensionPackage::get()->byID($this->args['id']));
	}

}

<?php
/**
 * A background job which builds a single extension.
 */
class BuildExtensionJob {

	public function setUp() {
		global $databaseConfig;

		if (!DB::isActive()) {
			DB::connect($databaseConfig);
		}
	}

	public function perform() {
		$package = ExtensionPackage::get()->byID($this->args['id']);
		$builder = Injector::inst()->get('ExtensionBuilder');

		$builder->build($package);

		$package->BuildQueued = false;
		$package->write();
	}

}

Clear the queued flag when a build job is executed


<?php

namespace spec\Eadrax\Core\Data;

trait Core
{
    function it_should_be_able_to_define_ids()
    {
        $this->set_id('foo');
        $this->get_id()->shouldBe('foo');
    }

    function it_should_be_able_to_construct_attributes()
    {
        $this->beConstructedWith(array('id' => 'foo'));
        $this->get_id()->shouldBe('foo');
    }
}

<?php

namespace spec\Eadrax\Core\Data;

trait Core
{
    function it_should_be_able_to_define_ids()
    {
        $this->set_id('foo');
        $this->get_id()->shouldBe('foo');
    }

    function it_should_be_able_to_construct_attributes()
    {
        $this->beConstructedWith(array('id' => 'foo'));
        $this->get_id()->shouldBe('foo');
    }

    function it_can_check_whether_or_not_data_has_been_set()
    {
        $this->beConstructedWith();
        $this->exists()->shouldBe(FALSE);

        $this->set_id('foo');
        $this->exists()->shouldBe(TRUE);
    }
}

Add test for core data exists() function.


<?php

namespace Queue\Queue;

use Cake\Core\Configure;

class Config {

	/**
	 * @return int
	 */
	public static function defaultworkertimeout() {
		return Configure::read('Queue.defaultworkertimeout', 1800); // 1h
	}

	/**
	 * @return int
	 */
	public static function workermaxruntime() {
		return Configure::read('Queue.workermaxruntime', 120);
	}

	/**
	 * @return int
	 */
	public static function cleanuptimeout() {
		return Configure::read('Queue.cleanuptimeout', 2592000); // 30 days
	}

	/**
	 * @return int
	 */
	public static function sleeptime() {
		return Configure::read('Queue.sleeptime', 10);
	}

	/**
	 * @return int
	 */
	public static function gcprob() {
		return Configure::read('Queue.gcprob', 10);
	}

	/**
	 * @return int
	 */
	public static function defaultworkerretries() {
		return Configure::read('Queue.defaultworkerretries', 1);
	}

	/**
	 * @return int
	 */
	public static function maxworkers()
	{
		return Configure::read('Queue.maxworkers', 1);
	}

}

Simplify usage by defaulting all configs.


<?php

namespace Torann\MediaSort\Disks;

class Local extends AbstractDisk
{
    /*
     * Used to determine if the path
     * has already been updated.
     *
     * @var string
     */
    private $root;

    /**
     * Remove an attached file.
     *
     * @param array $files
     */
    public function remove($files)
    {
        $this->setPathPrefix();

        parent::remove($files);
    }

    /**
     * Move an uploaded file to it's intended target.
     *
     * @param  string $source
     * @param  string $target
     *
     * @return void
     */
    public function move($source, $target)
    {
        $this->setPathPrefix();

        parent::move($source, $target);
    }

    /**
     * Set local path prefix from settings.
     *
     * @return void
     */
    protected function setPathPrefix()
    {
        if ($this->media->local_root && !$this->root) {
            // Interpolate path
            $this->root = $this->media->getInterpolator()
                ->interpolate($this->media->local_root);

            // Set path
            $this->filesystem->getDriver()
                ->getAdapter()
                ->setPathPrefix($this->root);
        }
    }
}

<?php

namespace Torann\MediaSort\Disks;

use Torann\MediaSort\Manager;
use Illuminate\Filesystem\FilesystemManager;

class Local extends AbstractDisk
{
    /**
     * Constructor method
     *
     * @param Manager           $media
     * @param FilesystemManager $filesystem
     */
    function __construct(Manager $media, FilesystemManager $filesystem)
    {
        parent::__construct($media, $filesystem);

        // Create a new instance of the local driver. Doing this will prevent
        // any setting changes made here from affecting the whole application.
        $this->filesystem = $filesystem->createLocalDriver($this->config);

        // Change the prefix of the local storage
        $this->setPathPrefix();
    }

    /**
     * Set local path prefix from settings.
     *
     * @return void
     */
    protected function setPathPrefix()
    {
        if ($this->media->local_root) {
            // Interpolate path
            $root = $this->media->getInterpolator()
                ->interpolate($this->media->local_root);

            // Set path
            $this->filesystem->getDriver()
                ->getAdapter()
                ->setPathPrefix($root);
        }
    }
}

Fix local storage config bug

Fix local storage config bug


<?php declare(strict_types = 1);

/**
 * This file is part of the jordanbrauer/unit-converter PHP package.
 *
 * @copyright 2018 Jordan Brauer <jbrauer.inc@gmail.com>
 * @license MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace UnitConverter\Unit\Time;

/**
 * Year unit data class.
 *
 * @version 2.0.0
 * @since 0.3.9
 * @author Teun Willems
 */
class Year extends TimeUnit
{
    protected function configure (): void
    {
        $this
            ->setName("year")

            ->setSymbol("y")

            ->setUnits(31536000)
            ;
    }
}

<?php declare(strict_types = 1);

/**
 * This file is part of the jordanbrauer/unit-converter PHP package.
 *
 * @copyright 2018 Jordan Brauer <jbrauer.inc@gmail.com>
 * @license MIT
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace UnitConverter\Unit\Time;

/**
 * Year unit data class.
 *
 * @version 2.0.0
 * @since 0.3.9
 * @author Teun Willems
 */
class Year extends TimeUnit
{
    protected function configure (): void
    {
        $this
            ->setName("year")

            ->setSymbol("y")

            ->setUnits(31536000)
            ;
    }

    /**
     * Determines if the given (or current, if non supplied) year is a leap year.
     *
     * @param integer $year The year being checked.
     * @return boolean
     */
    public static function isLeapYear (int $year = null): bool
    {
        $year = ($year ?? date('Y'));

        return (
            (0 == ($year % 4))
            && ((0 != ($year % 100)) XOR (0 == ($year % 400)))
        );
    }
}

Implement helper method to determine if year is leap year


<?php
/**
 * Created by PhpStorm.
 * User: visa
 * Date: 08/07/15
 * Time: 15.28
 */

namespace MailMan\Service;

class MailServiceAwareTrait
{
    protected $mailService;

    /**
     * @return null|MailInterface
     */
    public function getMailService()
    {
        return $this->mailService;
    }

    /**
     * @param MailInterface $mailService
     * @return $this
     */
    public function setMailService(MailInterface $mailService)
    {
        $this->mailService = $mailService;
        return $this;
    }

}

Fix Interface and trait aware service

Fix Interface and trait aware service


<?php namespace Octommerce\Octommerce\Components;

use Cms\Classes\ComponentBase;
use Octommerce\Octommerce\Models\Product as ProductModel;

class ProductDetail extends ComponentBase
{

    public function componentDetails()
    {
        return [
            'name'        => 'ProductDetail Component',
            'description' => 'No description provided yet...'
        ];
    }

    public function defineProperties()
    {
        return [
            'slug' => [
                'title'       => 'octommerce.octommerce::lang.component.product_detail.param.id_param_title',
                'description' => 'octommerce.octommerce::lang.component.product_detail.param.id_param_desc',
                'default'     => '{{ :slug }}',
                'type'        => 'string'
            ],
        ];
    }

    public function onRun()
    {
        $product = $this->loadProduct();

        if (!$product) {
            $this->setStatusCode(404);
            return $this->controller->run('404');
        }

        $this->product = $this->page['product'] = $product;

        $this->page->title = $product->name;
        $this->page->description = $product->description;
    }

    public function onChangeVariation()
    {

    }

    protected function loadProduct()
    {
        $slug = $this->property('slug');

        $product = ProductModel::whereSlug($slug)
            ->whereIsPublished(1)
            ->with('categories')
            ->with('lists')
            ->with('reviews')
            ->first();

        if ($product->type == 'variable') {

        }

        return $product;
    }

}

<?php namespace Octommerce\Octommerce\Components;

use Cms\Classes\ComponentBase;
use Octommerce\Octommerce\Models\Product as ProductModel;

class ProductDetail extends ComponentBase
{

    public function componentDetails()
    {
        return [
            'name'        => 'ProductDetail Component',
            'description' => 'No description provided yet...'
        ];
    }

    public function defineProperties()
    {
        return [
            'slug' => [
                'title'       => 'octommerce.octommerce::lang.component.product_detail.param.id_param_title',
                'description' => 'octommerce.octommerce::lang.component.product_detail.param.id_param_desc',
                'default'     => '{{ :slug }}',
                'type'        => 'string'
            ],
        ];
    }

    public function onRun()
    {
        $product = $this->loadProduct();

        if (!$product) {
            $this->setStatusCode(404);
            return $this->controller->run('404');
        }

        $this->product = $this->page['product'] = $product;

        $this->page->title = $product->name;
        $this->page->description = $product->description;
    }

    public function onChangeVariation()
    {

    }

    protected function loadProduct()
    {
        $slug = $this->property('slug');

        $product = ProductModel::whereSlug($slug)
            ->whereIsPublished(1)
            ->with('categories')
            ->with('lists')
            ->with('reviews')
            ->first();

        // if ($product->type == 'variable') {
        //
        // }

        return $product;
    }

}

Fix get non-object on product detail

Fix get non-object on product detail


<?php

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

define('MANALIZE_DIR', __DIR__);
define('MANALIZE_TMP_ROOT_DIR', sys_get_temp_dir().'/Manala');
define('UPDATE_FIXTURES', filter_var(getenv('UPDATE_FIXTURES'), FILTER_VALIDATE_BOOLEAN));

/**
 * Creates a unique tmp dir.
 *
 * @param string $prefix
 *
 * @return string The path to the tmp dir created
 */
function manala_get_tmp_dir($prefix = '')
{
    $tmp = @tempnam(MANALIZE_TMP_ROOT_DIR, $prefix);
    unlink($tmp);
    mkdir($tmp, 0777, true);

    return $tmp;
}

<?php

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

define('MANALIZE_DIR', __DIR__);
define('MANALIZE_TMP_ROOT_DIR', sys_get_temp_dir().'/Manala');
define('UPDATE_FIXTURES', filter_var(getenv('UPDATE_FIXTURES'), FILTER_VALIDATE_BOOLEAN));

/**
 * Creates a unique tmp dir.
 *
 * @param string $prefix
 *
 * @return string The path to the tmp dir created
 */
function manala_get_tmp_dir($prefix = '')
{
    if (!is_dir(MANALIZE_TMP_ROOT_DIR)) {
        @mkdir(MANALIZE_TMP_ROOT_DIR);
    }

    $tmp = @tempnam(MANALIZE_TMP_ROOT_DIR, $prefix);
    unlink($tmp);
    mkdir($tmp, 0777, true);

    return $tmp;
}

Fix manala_get_tmp_dir parsing the whole tmp directory


<!DOCTYPE html>

	<meta charset="UTF-8">

		<title>Time Crunchers Index</title>

TimeCrunchers Timeline

Data Design

					Conceptual Model

					ERD

					System Goals

					Use Cases

Personas

					Bob

					Hugh Allen

					Lucille

					Suzy

					Talia

					User Stories

Put suzy's use case in the proper place.


<?php
namespace Concrete\Package\KintDebug;

use Concrete\Core\Package\Package;
use View;

defined('C5_EXECUTE') or die(_("Access Denied."));

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

class Controller extends Package {
    protected $pkgHandle = 'kint_debug';
    protected $appVersionRequired = '5.7';
    protected $pkgVersion = '0.9.0';

    public function getPackageDescription() {
        return t('Add Kint debugging tools');
    }

    public function getPackageName() {
        return t('Kint Debug');
    }

    public function on_start() {
        $al = \Concrete\Core\Asset\AssetList::getInstance();
        $al->register('css', $this->pkgHandle . '/css', 'css/debug.css', array(), $this->pkgHandle);
        View::getInstance()->requireAsset('css', $this->pkgHandle . '/css');
    }
}

<?php
namespace Concrete\Package\KintDebug;

use Concrete\Core\Package\Package;
use View;

defined('C5_EXECUTE') or die(t("Access Denied."));

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

class Controller extends Package {
    protected $pkgHandle = 'kint_debug';
    protected $appVersionRequired = '5.7';
    protected $pkgVersion = '0.9.0';

    public function getPackageDescription() {
        return t('Add Kint debugging tools');
    }

    public function getPackageName() {
        return t('Kint Debug');
    }

    public function on_start() {
        $al = \Concrete\Core\Asset\AssetList::getInstance();
        $al->register('css', $this->pkgHandle . '/css', 'css/debug.css', array(), $this->pkgHandle);
        View::getInstance()->requireAsset('css', $this->pkgHandle . '/css');
    }
}

Use t instead of _

Use t instead of _


<?php

$path_extra = dirname(dirname(__FILE__)) . '/lib';

$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

require_once('SimpleSAML/Configuration.php');

SimpleSAML_Configuration::init(dirname(dirname(__FILE__)) . '/config');

?>

<?php

/* Remove magic quotes. */
if(get_magic_quotes_gpc()) {
	foreach(array('_GET', '_POST', '_COOKIE', '_REQUEST') as $a) {
		foreach($$a as &$v) {

			/* We don't use array-parameters anywhere.
			 * Ignore any that may appear.
			 */
			if(is_array($v)) {
				continue;
			}

			/* Unescape the string. */
			$v = stripslashes($v);
		}
	}
}

$path_extra = dirname(dirname(__FILE__)) . '/lib';

$path = ini_get('include_path');
$path = $path_extra . PATH_SEPARATOR . $path;
ini_set('include_path', $path);

require_once('SimpleSAML/Configuration.php');

SimpleSAML_Configuration::init(dirname(dirname(__FILE__)) . '/config');

?>

Remove magic quotes as a part of the initialization of simpleSAMLphp.


<?php
/**
 * The Event class is used as the base class for the creation of Event objects, which are passed as parameters to event handlers when an event is triggered.
 * The properties of the event carry basic information about an event.
 * An Event can carry information and state around the application. We can bind- _&referenced_- variables so that they can be modified through the event's live cycle.
 *
 *
 * @package     GDispatcher
 * @author      Emiliano Burgos <hello@goliatone.com>
 * @copyright   (c) 20011 Emiliano Burgos
 * @license     http://kohanaphp.com/license
 */
namespace goliatone\events;

use goliatone\events\core\CoreEvent;

class Event extends CoreEvent
{
    /**
     * Convenience method to trigger this event.
     * We can set if the event propagation can be stopped.
     * If no dispatcher is provided will use global dispatcher [Dispatcher::instance()](api/Dispatcher#instance)
     *
     * @param boolean $allow_stop_propagation Arguments for this event
     * @param Dispatcher $dispatcher Arguments for this event
     */
    public function dispatch($allow_stop_propagation = FALSE, $dispatcher = NULL)
    {
        // print "Event::dispatch\n";
        $dispatcher = $dispatcher == NULL ? Dispatcher::instance() : $dispatcher;
        $dispatcher->dispatch_event($this,$allow_stop_propagation);
    }
}

<?php
/**
 * The Event class is used as the base class for the creation of Event objects, which are passed as parameters to event handlers when an event is triggered.
 * The properties of the event carry basic information about an event.
 * An Event can carry information and state around the application. We can bind- _&referenced_- variables so that they can be modified through the event's live cycle.
 *
 *
 * @package     GDispatcher
 * @author      Emiliano Burgos <hello@goliatone.com>
 * @copyright   (c) 20011 Emiliano Burgos
 * @license     http://kohanaphp.com/license
 */
namespace goliatone\events;

use goliatone\events\core\CoreEvent;

class Event extends CoreEvent
{
    /**
     * Convenience method to trigger this event.
     * We can set if the event propagation can be stopped.
     * If no dispatcher is provided will use global dispatcher [Dispatcher::instance()](api/Dispatcher#instance)
     *
     * @param boolean $allow_stop_propagation Arguments for this event
     * @param Dispatcher $dispatcher Arguments for this event
     */
    public function dispatch($allow_stop_propagation = FALSE, $dispatcher = NULL)
    {
        // print "Event::dispatch\n";
        $dispatcher = $dispatcher == NULL ? Dispatcher::instance() : $dispatcher;
        $dispatcher->dispatch_event($this, $allow_stop_propagation);
    }
}

Fix space in method call.

Fix space in method call.