<?php declare(strict_types = 1);

namespace Cmnty\Push;

use Cmnty\Push\Crypto\Cryptograph;
use GuzzleHttp\Client as HttpClient;
use Psr\Http\Message\ResponseInterface;

class Client implements PushClient
{
    /**
     * @var PushService
     */
    private $pushService;

    /**
     * @var Client
     */
    private $httpClient;

    /**
     * Constructor.
     *
     * @param PushService $pushService
     * @param HttpClient $httpClient
     * @param Cryptograph $cryptograph
     */
    public function __construct(PushService $pushService, HttpClient $httpClient = null, Cryptograph $cryptograph = null)
    {
        $this->pushService = $pushService;
        $this->httpClient = $httpClient ?: new HttpClient();
        $this->cryptograph = $cryptograph ?: new Cryptograph();
    }

    /**
     * Send a push notification.
     *
     * @param PushNotification $notification
     * @param PushSubscription $subscription
     *
     * @param ResponseInterface
     */
    public function pushNotification(PushNotification $notification, PushSubscription $subscription)
    {
        $cipher = $this->cryptograph->encrypt($notification, $subscription);

        $pushMessage = new Message($cipher, $subscription);

        $request = $this->pushService->createRequest($pushMessage, $subscription);
        $response = $this->httpClient->send($request);

        return $response;
    }
}

<?php declare(strict_types = 1);

namespace Cmnty\Push;

use Cmnty\Push\Crypto\Cryptograph;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;

class Client implements PushClient
{
    /**
     * @var PushService
     */
    private $pushService;

    /**
     * @var Client
     */
    private $httpClient;

    /**
     * Constructor.
     *
     * @param PushService $pushService
     * @param HttpClient $httpClient
     * @param Cryptograph $cryptograph
     */
    public function __construct(PushService $pushService, HttpClient $httpClient = null, Cryptograph $cryptograph = null)
    {
        $this->pushService = $pushService;
        $this->httpClient = $httpClient ?: new HttpClient();
        $this->cryptograph = $cryptograph ?: new Cryptograph();
    }

    /**
     * Send a push notification.
     *
     * @param PushNotification $notification
     * @param PushSubscription $subscription
     *
     * @return ResponseInterface
     */
    public function pushNotification(PushNotification $notification, PushSubscription $subscription)
    {
        return $this->pushNotificationAsync($notification, $subscription)->wait();
    }

    /**
     * Send a push notification asynchronously.
     *
     * @param PushNotification $notification
     * @param PushSubscription $subscription
     *
     * @return PromiseInterface
     */
    public function pushNotificationAsync(PushNotification $notification, PushSubscription $subscription)
    {
        $cipher = $this->cryptograph->encrypt($notification, $subscription);

        $pushMessage = new Message($cipher, $subscription);

        $request = $this->pushService->createRequest($pushMessage, $subscription);
        $promise = $this->httpClient->sendAsync($request);

        return $promise;
    }
}

Allow notifications to be send async

Allow notifications to be send async


<?php
class Kwf_Component_Partial_Abstract
{
    protected $_params;

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

    public function getIds()
    {
        return array();
    }

    public function getParam($param, $necessary = true)
    {
        if ($necessary && !isset($this->_params[$param]))
            throw new Kwf_Exception('Param needed for Partial: ' . $param);
        if (!isset($this->_params[$param])) return null;
        return $this->_params[$param];
    }

    public static function useViewCache($componentId, $params)
    {
        if (isset($params['disableCache']) && $params['disableCache']) {
            return false;
        }
        if (isset($params['disableCacheParams'])) {
            return array(
                'callback' => array(
                    'Kwf_Component_Partial_Abstract',
                    '_useViewCacheDynamic'
                ),
                'args' => array(
                    $params['disableCacheParams']
                )
            );
        }
        return true;
    }

    public function _useViewCacheDynamic($disableCacheParams)
    {
        foreach ($disableCacheParams as $param) {
            if (isset($_REQUEST[$param])) return false;
        }
        return true;
    }
}

<?php
class Kwf_Component_Partial_Abstract
{
    protected $_params;

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

    public function getIds()
    {
        return array();
    }

    public function getParam($param, $necessary = true)
    {
        if ($necessary && !isset($this->_params[$param]))
            throw new Kwf_Exception('Param needed for Partial: ' . $param);
        if (!isset($this->_params[$param])) return null;
        return $this->_params[$param];
    }

    public static function useViewCache($componentId, $params)
    {
        if (isset($params['disableCache']) && $params['disableCache']) {
            return false;
        }
        if (isset($params['disableCacheParams'])) {
            return array(
                'callback' => array(
                    'Kwf_Component_Partial_Abstract',
                    '_useViewCacheDynamic'
                ),
                'args' => array(
                    $params['disableCacheParams']
                )
            );
        }
        return true;
    }

    public static function _useViewCacheDynamic($disableCacheParams)
    {
        foreach ($disableCacheParams as $param) {
            if (isset($_REQUEST[$param])) return false;
        }
        return true;
    }
}

Make method static as it is called statically


<?php

require_once '../lib/Encaminar.php';

class FrontController
{
    /** @Route("GET /") */
    public function index()
    {
        return "Home";
    }
    /** @Route("GET /hello") */
    public function hello()
    {
        return "Hello";
    }
}

$encaminar = new Encaminar();
$url = strrchr($_SERVER['REQUEST_URI'], '/~albo/pragmore/2011/rubra/logistica/workspace/Encaminar/demo');
$encaminar->setUrl($url)->setHttpMethod($_SERVER['REQUEST_METHOD']);
echo $encaminar(new FrontController);

<?php

define('BASE_PATH', '/~albo/pragmore/2011/rubra/logistica/workspace/Encaminar/demo');

require_once '../lib/Encaminar.php';

class FrontController
{
    /** @Route("GET /") */
    public function index()
    {
        $this->_render("Welcome!");
    }
    /** @Route("GET /hello/:name") */
    public function hello($params)
    {
        $this->_render("Hello " . $params['name']);
    }

    private function _render($message)
    {
    	$base = BASE_PATH;
		echo <<<EOHTML

Encaminar

A PHP routing library

			Home
			Hello world
			Hello hello

$message

EOHTML;
    }
}

$encaminar = new Encaminar();
$encaminar->setBasePath(BASE_PATH)
          ->setUrl($_SERVER['REQUEST_URI'])
          ->setHttpMethod($_SERVER['REQUEST_METHOD']);

$encaminar(new FrontController);

Add dynamic example and HTML to demo

Add dynamic example and HTML to demo


<?php

namespace App\Repositories;

use App\Models\Activity;
use Illuminate\Database\Eloquent\Collection;

class ActivityRepository
{
    /**
     * @var mixed
     */
    protected $model;

    /**
     * @param Activity $activity
     */
    public function __construct(Activity $activity)
    {
        $this->model = $activity;
    }

    /**
     * Return all company wide activities.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getAllActivities(): Collection
    {
        $query = $this->model->with(['causer:id,name,username', 'subject:id,name']);
        $query = request('user') ? $query->where('causer_id', request('user')) : $query;
        $query = request('date') ? $query->whereDate('created_at', request('date')) : $query;

        return $query->get()->groupBy('date');
    }
}

<?php

namespace App\Repositories;

use App\Models\Activity;
use Illuminate\Database\Eloquent\Collection;

class ActivityRepository
{
    /**
     * @var mixed
     */
    protected $model;

    /**
     * @param Activity $activity
     */
    public function __construct(Activity $activity)
    {
        $this->model = $activity;
    }

    /**
     * Return all company wide activities.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getAllActivities(): Collection
    {
        $query = $this->model->with(['causer:id,name,username', 'subject:id,name,created_at']);
        $query = request('user') ? $query->where('causer_id', request('user')) : $query;
        $query = request('date') ? $query->whereDate('created_at', request('date')) : $query;

        return $query->get()->groupBy('date');
    }
}

Fix - call function on null in activity api


<?php

namespace Unicodeveloper\Identify\Test;

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Unicodeveloper\Identify\{ Identify, IdentifyServiceProvider };

class IdentifyServiceProviderTest extends TestCase
{

    /**
     * @var MockInterface
     */
    protected $mockApp;

    /**
     * @var IdentifyServiceProvider
     */
    protected $provider;

    protected function setUp()
    {
        parent::setUp();
        $this->mockApp = m::mock('\Illuminate\Contracts\Foundation\Application');
        $this->provider = new IdentifyServiceProvider($this->mockApp);
    }

    /**
     * Test that it registers the correct service name with Identity
     */
    public function testRegister()
    {
        $this->mockApp->shouldReceive('bind')
            ->once()
            ->andReturnUsing(function($name, $closure) {
                $this->assertEquals('laravel-identify', $name);
                $this->assertInstanceOf(Identify::class, $closure());
            });

        $this->provider->register();
    }

    /**
     * Test that it provides the correct service name
     */
    public function testProvides()
    {
        $expected = ['laravel-identify'];
        $actual = $this->provider->provides();

        $this->assertEquals($expected, $actual);
    }
}

<?php

namespace Unicodeveloper\Identify\Test;

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Unicodeveloper\Identify\{ Identify, IdentifyServiceProvider };

class IdentifyServiceProviderTest extends TestCase
{

    /**
     * @var MockInterface
     */
    protected $mockApp;

    /**
     * @var IdentifyServiceProvider
     */
    protected $provider;

    protected function setUp(): void
    {
        parent::setUp();
        $this->mockApp = m::mock('\Illuminate\Contracts\Foundation\Application');
        $this->provider = new IdentifyServiceProvider($this->mockApp);
    }

    /**
     * Test that it registers the correct service name with Identity
     */
    public function testRegister()
    {
        $this->mockApp->shouldReceive('bind')
            ->once()
            ->andReturnUsing(function($name, $closure) {
                $this->assertEquals('laravel-identify', $name);
                $this->assertInstanceOf(Identify::class, $closure());
            });

        $this->provider->register();
    }

    /**
     * Test that it provides the correct service name
     */
    public function testProvides()
    {
        $expected = ['laravel-identify'];
        $actual = $this->provider->provides();

        $this->assertEquals($expected, $actual);
    }
}

fix(identify): Make setUp method compatible with PHPUnit TestCase


<?php
/**
 * notification_InitializeSiteNotifPanelAction
 * @package modules.notification.actions
 */
class notification_InitializeSiteNotifPanelAction extends f_action_BaseJSONAction
{
	/**
	 * @param Context $context
	 * @param Request $request
	 */
	public function _execute($context, $request)
	{
		$result = array('notif' => array(), 'website' => array());
		$notification = $this->getDocumentInstanceFromRequest($request);
		$notifs = notification_SitenotificationService::getInstance()
			->createQuery()->add(Restrictions::childOf($notification->getId()))->find();

		$usedWebsite = array(0);

		foreach ($notifs as $notif)
		{
			$website = $notif->getWebsite();
			$usedWebsite[] = $website->getId();
			$info = array('id' => $notif->getId(),
						'websiteid' => $website->getId(),
						'website' => $website->getLabel(),
						'status' => f_Locale::translateUI(DocumentHelper::getPublicationstatusLocaleKey($notif))
			);
			$result['notif'][] = $info;
		}

		$result['website'] = website_WebsiteService::getInstance()->createQuery()
			->add(Restrictions::notin('id', $usedWebsite))
			->setProjection(Projections::property('id', 'id'), Projections::property('label', 'label'))
			->find();

		return $this->sendJSON($result);
	}
}

<?php
/**
 * notification_InitializeSiteNotifPanelAction
 * @package modules.notification.actions
 */
class notification_InitializeSiteNotifPanelAction extends f_action_BaseJSONAction
{
	/**
	 * @param Context $context
	 * @param Request $request
	 */
	public function _execute($context, $request)
	{
		$result = array('notif' => array(), 'website' => array());
		$notification = $this->getDocumentInstanceFromRequest($request);
		$notifs = notification_SitenotificationService::getInstance()
			->createQuery()->add(Restrictions::childOf($notification->getId()))->find();

		$usedWebsite = array(0);

		foreach ($notifs as $notif)
		{
			$website = $notif->getWebsite();
			$usedWebsite[] = $website->getId();
			$info = array('id' => $notif->getId(),
						'websiteid' => $website->getId(),
						'website' => $website->getLabel(),
						'status' => f_Locale::translateUI(DocumentHelper::getPublicationstatusLocaleKey($notif))
			);
			$result['notif'][] = $info;
		}

		foreach (website_WebsiteService::getInstance()->createQuery()->add(Restrictions::notin('id', $usedWebsite))->find() as $website)
		{
			/* @var $website website_persistentdocument_website */
			$result['website'][] = array('id' => $website->getId(), 'label' => ($website->isContextLangAvailable() ? $website->getLabel() : $website->getVoLabel()));
		}
		return $this->sendJSON($result);
	}
}

[FIX] Fix on website list when site is not localized


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SMSInboundController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		$query = $request->query;
		//$msisdn = $query->msisdn;

		return new Response('OK', 200);
	}

	public function callbackAction(Request $request = NULL)
	{
		$query = $request->query;
		//$msisdn = $query->msisdn;

		return new Response('OK', 200);
	}
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SMSInboundController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		$query = $request->query;
		//$msisdn = $query->msisdn;

		$phone = 1234;

		$message = \Swift_Message::newInstance()
		->setSubject('Telefono movil ' . $phone . ' verificado correctamenet')
		->setFrom('verificaciones@municipales2015.listabierta.org')
		->setTo($this->container->getParameter('admin_email'))
		->setBody(
				$this->renderView(
						'MunicipalesBundle:Mail:sms_inbound_verification.html.twig',
						array('phone' => $phone)
				)
		)
		;
		$this->get('mailer')->send($message);

		return new Response('OK', 200);
	}

	public function callbackAction(Request $request = NULL)
	{
		$query = $request->query;
		//$msisdn = $query->msisdn;

		return new Response('OK', 200);
	}
}

Send a email as test in sms inbound

Send a email as test in sms inbound


<?php

namespace Oro\Bundle\ActionBundle\Tests\Unit\Command;

use Oro\Bundle\ActionBundle\Command\DebugConditionCommand;

class DebugConditionCommandTest extends AbstractDebugCommandTestCase
{
    public function testConfigure()
    {
        $this->assertNotEmpty($this->command->getDescription());
        $this->assertNotEmpty($this->command->getHelp());
        $this->assertEquals(DebugConditionCommand::COMMAND_NAME, $this->command->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function getFactoryServiceId()
    {
        return DebugConditionCommand::FACTORY_SERVICE_ID;
    }

    /**
     * {@inheritdoc}
     */
    public function getArgumentName()
    {
        return DebugConditionCommand::ARGUMENT_NAME;
    }

    /**
     * {@inheritdoc}
     */
    public function getCommandInstance()
    {
        return new DebugConditionCommand();
    }
}

<?php

namespace Oro\Bundle\ActionBundle\Tests\Unit\Command;

use Oro\Bundle\ActionBundle\Command\DebugConditionCommand;

class DebugConditionCommandTest extends AbstractDebugCommandTestCase
{
    public function testConfigure()
    {
        $this->assertNotEmpty($this->command->getDescription());
        $this->assertNotEmpty($this->command->getHelp());
        $this->assertEquals(DebugConditionCommand::COMMAND_NAME, $this->command->getName());
    }

    /**
     * {@inheritdoc}
     */
    protected function getFactoryServiceId()
    {
        return DebugConditionCommand::FACTORY_SERVICE_ID;
    }

    /**
     * {@inheritdoc}
     */
    protected function getArgumentName()
    {
        return DebugConditionCommand::ARGUMENT_NAME;
    }

    /**
     * {@inheritdoc}
     */
    protected function getCommandInstance()
    {
        return new DebugConditionCommand();
    }
}

BAP-12009: Create command oro:debug:condition
 - CR fixes


<?php

/**
 * Class UnitsController
 * Actions related to dealing with units
 * @author Stuart Chalk <schalk@unf.edu>
 *
 */
class UnitsController extends AppController
{

    public $uses=['Unit'];

    /**
     * beforeFilter function
     */
    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow();
    }

    /**
     * List the quantities
     * @param $qid - quantityID
     */
    public function index($qid="",$format="")
    {
        if($qid=="") {
            $data=$this->Unit->find('list',['fields'=>['id','name'],'order'=>['name']]);
        } else {
            $data=$this->Unit->find('list',['fields'=>['id','name'],'conditions'=>['quantity_id'=>$qid],'order'=>['name']]);
        }
        //echo "
";print_r($data);echo "
";exit;
        if($format=="json") { echo json_encode($data); exit; }
        $this->set('data',$data);
    }

    /**
     * Regex test function
     */
    public function regex()
    {
        $s="05 Nov 2007 17:38:45";
        $r="/^([0-9]{1,2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/";
        preg_match($r,$s,$m);
        debug($m);exit;
    }

    /**
     * JSON test function
     */
    public function jsona()
    {
        $data=file_get_contents(WWW_ROOT.'/scidata_spectrum.txt');
        echo "
";json_decode("[".$data."]");echo "
";exit;
    }

}

<?php

/**
 * Class UnitsController
 * Actions related to dealing with units
 * @author Stuart Chalk <schalk@unf.edu>
 *
 */
class UnitsController extends AppController
{

    public $uses=['Unit'];

    /**
     * beforeFilter function
     */
    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow();
    }

    /**
     * List the quantities
     * @param $qid - quantityID
     */
    public function index($qid="",$format="")
    {
        if($qid=="") {
            $data=$this->Unit->find('list',['fields'=>['id','name'],'order'=>['name']]);
        } else {
            $data=$this->Unit->find('list',['fields'=>['id','name'],'conditions'=>['quantity_id'=>$qid],'order'=>['name']]);
        }
        if($format=="json") { echo json_encode($data); exit; }
        $this->set('data',$data);
    }

    /**
     * Regex test function
     */
    public function regex()
    {
        $s="05 Nov 2007 17:38:45";
        $r="/^([0-9]{1,2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/";
        preg_match($r,$s,$m);
        debug($m);exit;
    }

}

Update because CakePHP version changed

Update because CakePHP version changed


<?php
namespace Maphper\Lib;
//Replaces dates in an object graph with \DateTime instances
class DateInjector {
	private $processCache;

	public function replaceDates($obj, $reset = true) {
		//prevent infinite recursion, only process each object once
		if ($reset) $this->processCache = new \SplObjectStorage();
		if (is_object($obj) && $this->processCache->contains($obj)) return $obj;
		else if (is_object($obj)) $this->processCache->attach($obj, true);

		if (is_array($obj) || (is_object($obj) && ($obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false);
		if (is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20) {
			try {
				$date = new \DateTime($obj);
				if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20)) $obj = $date;
			}
			catch (\Exception $e) {	//Doesn't need to do anything as the try/catch is working out whether $obj is a date
			}
		}
		return $obj;
	}
}

<?php
namespace Maphper\Lib;
//Replaces dates in an object graph with \DateTime instances
class DateInjector {
	private $processCache;

	public function replaceDates($obj, $reset = true) {
		//prevent infinite recursion, only process each object once
		if ($reset) $this->processCache = new \SplObjectStorage();
		if (is_object($obj) && $this->processCache->contains($obj)) return $obj;
		else if (is_object($obj)) $this->processCache->attach($obj, true);

		if (is_array($obj) || (is_object($obj) && ($obj instanceof \Iterator))) foreach ($obj as &$o) $o = $this->replaceDates($o, false);
		if (is_string($obj) && isset($obj[0]) && is_numeric($obj[0]) && strlen($obj) <= 20) {
			try {
				$date = new \DateTime($obj);
				if ($date->format('Y-m-d H:i:s') == substr($obj, 0, 20) || $date->format('Y-m-d') == substr($obj, 0, 10)) $obj = $date;
			}
			catch (\Exception $e) {	//Doesn't need to do anything as the try/catch is working out whether $obj is a date
			}
		}
		return $obj;
	}
}

Allow date without time with date injector


<?php

class CM_Tree_Language extends CM_Tree_Abstract {

	protected $_rootId = '.';

	/**
	 * @param array|null $params
	 */
	public function __construct($params = null) {
		parent::__construct('CM_TreeNode_Language', $params);
	}

	protected function _load() {
		$result = CM_Mysql::select(TBL_CM_LANGUAGEKEY, 'name', 'name LIKE ".%"');
		while ($section = $result->fetchAssoc()) {
			$this->_addLanguageNode($section['name']);
		}
	}

	/**
	 * @param string $languageKey
	 * @throws CM_Exception_Invalid
	 */
	private function _addLanguageNode($languageKey) {
		if (!preg_match('#^(.*)\.([^\.]+)$#', $languageKey , $matches)) {
			throw new CM_Exception_Invalid('Invalid Language Key found: `' . $languageKey . '`');
		}
		list($id, $parentId, $name) = $matches;
		if ($parentId && !array_key_exists($parentId, $this->_nodesTmp)) {
			$this->_addLanguageNode($parentId);
		}
		if (!$parentId) {
			$parentId = $this->_rootId;
		}
		parent::_addNode($id, $name, $parentId);
	}

}

<?php

class CM_Tree_Language extends CM_Tree_Abstract {

	protected $_rootId = '.';

	/**
	 * @param array|null $params
	 */
	public function __construct($params = null) {
		parent::__construct('CM_TreeNode_Language', $params);
	}

	protected function _load() {
		$result = CM_Mysql::select(TBL_CM_LANGUAGEKEY, 'name', 'name LIKE ".%"', 'name ASC');
		while ($section = $result->fetchAssoc()) {
			$this->_addLanguageNode($section['name']);
		}
	}

	/**
	 * @param string $languageKey
	 * @throws CM_Exception_Invalid
	 */
	private function _addLanguageNode($languageKey) {
		if (!preg_match('#^(.*)\.([^\.]+)$#', $languageKey , $matches)) {
			throw new CM_Exception_Invalid('Invalid Language Key found: `' . $languageKey . '`');
		}
		list($id, $parentId, $name) = $matches;
		if ($parentId && !array_key_exists($parentId, $this->_nodesTmp)) {
			$this->_addLanguageNode($parentId);
		}
		if (!$parentId) {
			$parentId = $this->_rootId;
		}
		parent::_addNode($id, $name, $parentId);
	}

}

Order language tree by key name

t285: Order language tree by key name


@section('js')
    <script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script>
@endsection

@include('core::admin._buttons-form')

{!! BootForm::hidden('id') !!}

{!! BootForm::text(__('Name'), 'name') !!}

{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}

</div>

@section('js')
    <script src="{{ asset('components/ckeditor/ckeditor.js') }}"></script>
@endsection

@component('core::admin._buttons-form', ['model' => $model])
@endcomponent

{!! BootForm::hidden('id') !!}

{!! BootForm::text(__('Name'), 'name') !!}

{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor') !!}

</div>

Use of @component for buttons in form

Use of @component for buttons in form


<?php

/*
 * This file is part of the PcdxParameterEncryptionBundle package.
 *
 * (c) picodexter <https://picodexter.io/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Picodexter\ParameterEncryptionBundle\DependencyInjection;

/**
 * ServiceNames.
 *
 * Contains names for this bundle's Symfony services that are referenced in the code.
 */
final class ServiceNames
{
    const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration';
    const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.';
    const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer';
    const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.';
    const REPLACEMENT_PATTERN_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.registry';
    const REPLACEMENT_PATTERN_TYPE_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.type_registry';
    const REPLACEMENT_SOURCE_DECRYPTER_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.source.decrypter.';

    /**
     * Constructor.
     *
     * Forbid instantiation.
     */
    public function __construct()
    {
        throw new \BadMethodCallException('This class cannot be instantiated.');
    }
}

<?php

/*
 * This file is part of the PcdxParameterEncryptionBundle package.
 *
 * (c) picodexter <https://picodexter.io/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Picodexter\ParameterEncryptionBundle\DependencyInjection;

/**
 * ServiceNames.
 *
 * Contains names for this bundle's Symfony services that are referenced in the code.
 */
final class ServiceNames
{
    const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration';
    const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.';
    const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer';
    const PARAMETER_REPLACEMENT_FETCHER = 'pcdx_parameter_encryption.replacement.parameter_replacement_fetcher';
    const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.';
    const REPLACEMENT_PATTERN_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.registry';
    const REPLACEMENT_PATTERN_TYPE_REGISTRY = 'pcdx_parameter_encryption.replacement.pattern.type_registry';
    const REPLACEMENT_SOURCE_DECRYPTER_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.source.decrypter.';

    /**
     * Constructor.
     *
     * Forbid instantiation.
     */
    public function __construct()
    {
        throw new \BadMethodCallException('This class cannot be instantiated.');
    }
}

Add service name for parameter replacement fetcher


<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));

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

//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/om' . PATH_SEPARATOR . get_include_path());
set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());

require_once 'CcMusicDirsQuery.php';

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../install_minimal/../airtime_mvc/application'));

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

//Propel classes.
set_include_path(APPLICATION_PATH . '/models' . PATH_SEPARATOR . get_include_path());
#set_include_path(APPLICATION_PATH . '/models/om' . PATH_SEPARATOR . get_include_path());
#set_include_path(APPLICATION_PATH . '/models/airtime' . PATH_SEPARATOR . get_include_path());

require_once 'CcMusicDirsQuery.php';
require_once 'BaseCcMusicDirsQuery.php';

class StorageQuotaUpgrade
{
    public static function startUpgrade()
    {
        echo "* Updating storage usage for new quota tracking".PHP_EOL;
        self::setStorageUsage();
    }

    private static function setStorageUsage()
    {
        $musicDir = CcMusicDirsQuery::create()
            ->filterByDbType('stor')
            ->filterByDbExists(true)
            ->findOne();
        $storPath = $musicDir->getDbDirectory();

        $freeSpace = disk_free_space($storPath);
        $totalSpace = disk_total_space($storPath);

        Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
    }
}

CC-5781: Upgrade script for new storage quota implementation


<?php
if (Request::getInstance()->get('_ccm_dashboard_external')) {
    return;
}
?>
</div>
</div>

<?php View::element('footer_required', ['disableTrackingCode' => true]); ?>
<script type="text/javascript">
(function() {
    ConcretePanelManager.register({'overlay': false, 'identifier': 'dashboard', 'position': 'right', url: '<?=URL::to('/ccm/system/panels/dashboard')?>'});
    ConcretePanelManager.register({'identifier': 'sitemap', 'position': 'right', url: '<?=URL::to('/ccm/system/panels/sitemap')?>'});
    var panel = ConcretePanelManager.getByIdentifier('dashboard');
    <?php
    if (!(isset($hideDashboardPanel) && $hideDashboardPanel)) {
        ?>
        panel.isOpen = true;
        panel.onPanelLoad();
        <?php
    }
    ?>
    ConcreteEvent.subscribe('PanelOpen', function(e, data) {
        if (data.panel === panel) {
            $.cookie('dashboardPanelStatus', null, {path: '<?=DIR_REL?>/'});
        }
    });
    ConcreteEvent.subscribe('PanelClose', function(e, data) {
        if (data.panel === panel) {
            $.cookie('dashboardPanelStatus', 'closed', {path: '<?=DIR_REL?>/'});
        }
    });
})();
</script>
</body>
</html>

<?php
if (Request::getInstance()->get('_ccm_dashboard_external')) {
    return;
}
?>
</div>
</div>

<?php View::element('footer_required', ['disableTrackingCode' => true]); ?>
<script type="text/javascript">
(function() {
    ConcretePanelManager.register({'overlay': false, 'identifier': 'dashboard', 'position': 'right', url: '<?=URL::to('/ccm/system/panels/dashboard')?>'});
    ConcretePanelManager.register({'identifier': 'sitemap', 'position': 'right', url: '<?=URL::to('/ccm/system/panels/sitemap')?>'});
    var panel = ConcretePanelManager.getByIdentifier('dashboard');
    <?php
    if (!(isset($hideDashboardPanel) && $hideDashboardPanel)) {
        ?>
        panel.isOpen = true;
        panel.onPanelLoad();
        <?php
    }
    ?>
    var savePanelStatus = false;
    ConcreteEvent.subscribe('PanelOpen', function(e, data) {
        if (savePanelStatus && data.panel === panel) {
            $.cookie('dashboardPanelStatus', null, {path: '<?=DIR_REL?>/'});
            savePanelStatus = false;
        }
    });
    ConcreteEvent.subscribe('PanelClose', function(e, data) {
        if (savePanelStatus && data.panel === panel) {
            $.cookie('dashboardPanelStatus', 'closed', {path: '<?=DIR_REL?>/'});
            savePanelStatus = false;
        }
    });
    $(document).ready(function() {
        $('a[data-launch-panel=dashboard]').on('click', function() {
            savePanelStatus = true;
        });
    });
})();
</script>
</body>
</html>

Save dashboard panel visibility only when needed


<?php

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

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name');
			$table->string('email')->unique()->nullable();
			$table->string('password', 60);
			$table->string('avatar')->nullable();
			$table->boolean('blocked')->default(false)->index();
			$table->integer('topic_count')->default(0)->index();
			$table->integer('reply_count')->default(0)->index();
			$table->string('city')->nullable();
			$table->string('website')->nullable();
			$table->string('signature')->nullable();
			$table->string('introduction')->nullable();
			$table->rememberToken();
			$table->softDeletes();
			$table->timestamps();
		});
	}

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

}

<?php

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

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('name');
			$table->string('email')->unique()->nullable();
			$table->string('password', 60);
			$table->string('avatar')->nullable();
			$table->boolean('blocked')->default(false)->index();
			$table->integer('topic_count')->default(0)->index();
			$table->integer('reply_count')->default(0)->index();
			$table->integer('notification_count')->default(0);
			$table->string('city')->nullable();
			$table->string('website')->nullable();
			$table->string('signature')->nullable();
			$table->string('introduction')->nullable();
			$table->rememberToken();
			$table->softDeletes();
			$table->timestamps();
		});
	}

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

}

Add notification count fields to the user table.


<?php

/**
 * Add here as many arguments as segments you want to be used on your URIs or as arguments to the
 * CLI runner.
 */

if(PHP_SAPI == 'cli') {
	$arguments_structure = array(
		'controller',
		'variable1',
	);
} else {
	// The url would be as follows http://yourserver.com/controller/variable1
	$url_structure = array(
		'controller',
		'variable1'
	);
}

<?php

/**
 * Add here as many arguments as segments you want to be used on your URIs or as arguments to the
 * CLI runner.
 */

if(PHP_SAPI == 'cli') {
	$arguments_structure = array(
		'controller',
		'website',
	);
} else {
	// The url would be as follows http://yourserver.com/controller/variable1
	$url_structure = array(
		'controller',
		'variable1'
	);
}

Use as 1st argument for CLI.

Use  as 1st argument for CLI.


<?php

namespace Basemkhirat\Elasticsearch;

use Illuminate\Support\Collection as BaseCollection;

class Collection extends BaseCollection
{

    /**
     * Get the collection of items as JSON.
     *
     * @param  int  $options
     * @return string
     */
    public function toJson($options = 0)
    {
        return json_encode($this->toArray(), $options);
    }

    /**
     * Get the collection of items as Array.
     *
     * @return string
     */
    public function toArray()
    {
        return array_map(function($item){
            return $item->toArray();
        }, $this->items);
    }

}

<?php

namespace Basemkhirat\Elasticsearch;

use Illuminate\Support\Collection as BaseCollection;

class Collection extends BaseCollection
{

    /**
     * Get the collection of items as JSON.
     *
     * @param  int  $options
     * @return string
     */
    public function toJson($options = 0)
    {
        return json_encode($this->toArray(), $options);
    }

}

Remove toArray as it is now handled by ArrayAccess


<?php

final class PhabricatorSetupCheckPygment extends PhabricatorSetupCheck {

  protected function executeChecks() {

    $pygment = PhabricatorEnv::getEnvConfig('pygments.enabled');

    if ($pygment) {
      list($err) = exec_manual('pygmentize -h');
      if ($err) {
        $summary = pht(
          'You enabled pygments but the pygmentize script is not '.
          'actually available, your $PATH is probably broken.');

        $message = pht(
          'The environmental variable $PATH does not contain '.
          'pygmentize. You have enabled pygments, which requires '.
          'pygmentize to be available in your $PATH variable.');

        $this
          ->newIssue('pygments.enabled')
          ->setName(pht('pygmentize Not Found'))
          ->setSummary($summary)
          ->setMessage($message)
          ->addPhabricatorConfig('pygments.enabled')
          ->addPhabricatorConfig('envinronment.append-paths');
      }
    }
  }
}

<?php

final class PhabricatorSetupCheckPygment extends PhabricatorSetupCheck {

  protected function executeChecks() {

    $pygment = PhabricatorEnv::getEnvConfig('pygments.enabled');

    if ($pygment) {
      list($err) = exec_manual('pygmentize -h');
      if ($err) {
        $summary = pht(
          'You enabled pygments but the pygmentize script is not '.
          'actually available, your $PATH is probably broken.');

        $message = pht(
          'The environmental variable $PATH does not contain '.
          'pygmentize. You have enabled pygments, which requires '.
          'pygmentize to be available in your $PATH variable.');

        $this
          ->newIssue('pygments.enabled')
          ->setName(pht('pygmentize Not Found'))
          ->setSummary($summary)
          ->setMessage($message)
          ->addPhabricatorConfig('pygments.enabled')
          ->addPhabricatorConfig('environment.append-paths');
      }
    }
  }
}

Fix config name typo in SetupCheckPygment

Summary:
Use correct spelling of 'environment.append-paths' so that the current
value of the variable will display as expected in the
'pygmentize Not Found' setup issue screen.

Test Plan:
* Enabled Pygments but haven't installed it
* Follow 'unresolved setup issues' link to 'Not Found' screen
* See that 'envinronment.append-paths' is None
* Set 'environment.append-paths'
* See that 'envinronment.append-paths' is still None
* Apply this fix
* See that 'environment.append-paths' is now '/usr/bin'

Reviewers: epriestley

Reviewed By: epriestley

CC: aran, Korvin

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


<?php
/**
 * customer_DynamiccustomergroupScriptDocumentElement
 * @package modules.customer.persistentdocument.import
 */
class customer_DynamiccustomergroupScriptDocumentElement extends import_ScriptDocumentElement
{
    /**
     * @return customer_persistentdocument_dynamiccustomergroup
     */
    protected function initPersistentDocument()
    {
    	return customer_DynamiccustomergroupService::getInstance()->getNewDocumentInstance();
    }

    /**
	 * @return f_persistentdocument_PersistentDocumentModel
	 */
	protected function getDocumentModel()
	{
		return f_persistentdocument_PersistentDocumentModel::getInstanceFromDocumentModelName('modules_customer/dynamiccustomergroup');
	}
}

<?php
/**
 * customer_DynamiccustomergroupScriptDocumentElement
 * @package modules.customer.persistentdocument.import
 */
class customer_DynamiccustomergroupScriptDocumentElement extends import_ScriptDocumentElement
{
    /**
     * @return customer_persistentdocument_dynamiccustomergroup
     */
    protected function initPersistentDocument()
    {
    	return customer_DynamiccustomergroupService::getInstance()->getNewDocumentInstance();
    }

    /**
	 * @return f_persistentdocument_PersistentDocumentModel
	 */
	protected function getDocumentModel()
	{
		return f_persistentdocument_PersistentDocumentModel::getInstanceFromDocumentModelName('modules_customer/dynamiccustomergroup');
	}

	/**
	 * @return array
	 */
	protected function getDocumentProperties()
	{
		$properties = parent::getDocumentProperties();
		if (isset($properties['query']))
		{
			$query = $this->replaceRefIdInString($properties['query']) ;
			$properties['query'] = $query;
		}
		return $properties;
	}
}

[NEW] Handle {ref-id:...} in XML import for query properties.


<?php

namespace Galahad\LaravelAddressing;

/**
 * Class AdministrativeAreaCollection
 *
 * @package Galahad\LaravelAddressing
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class AdministrativeAreaCollection extends Collection implements CollectionInterface
{
    /**
     * Return all the items ready for a <select> HTML element
     *
     * @return mixed
     */
    public function toList()
    {
        $items = [];
        /** @var AdministrativeArea $area */
        foreach ($this as $area) {
            $items[$area->getCode()] = $area->getName();
        }

        return $items;
    }
}

<?php

namespace Galahad\LaravelAddressing;

/**
 * Class AdministrativeAreaCollection
 *
 * @package Galahad\LaravelAddressing
 * @author Junior Grossi <juniorgro@gmail.com>
 */
class AdministrativeAreaCollection extends Collection implements CollectionInterface
{
    /**
     * Return all the items ready for a <select> HTML element
     *
     * @return mixed
     */
    public function toList()
    {
        $items = [];
        /** @var AdministrativeArea $area */
        foreach ($this as $area) {
            $items[$area->getCode()] = $area->getName();
        }

        return $items;
    }

    /**
     * Get an administrative are by code
     *
     * @param string $code
     * @return AdministrativeArea
     */
    public function findByCode($code)
    {
        /** @var AdministrativeArea $first */
        $first = $this->getByKey(0);

        return $first->findByCode($code);
    }

    /**
     * Get an administrative are by name
     *
     * @param string $name
     * @return AdministrativeArea
     */
    public function findByName($name)
    {
        $first = $this->getByKey(0);

        return $first->findByName($name);
    }
}

Add option to get an administrative area by code or name inside a collection


<?php
class Kwf_Validate_NoTags extends Zend_Validate_Abstract
{
    const INVALID_TAGS = 'invalidTags';

    public function __construct()
    {
        $this->_messageTemplates[self::INVALID_TAGS] = trlKwfStatic("Must not include tags");
    }

    public function isValid($value)
    {
        if (strip_tags($value) != $value || stripos($value, 'Content-Type:') !== false) {
            $this->_error(self::INVALID_TAGS);
            return false;
        }
        return true;
    }
}

<?php
class Kwf_Validate_NoTags extends Zend_Validate_Abstract
{
    const INVALID_TAGS = 'invalidTags';

    public function __construct()
    {
        $this->_messageTemplates[self::INVALID_TAGS] = trlKwfStatic("Must not include tags");
    }

    public function isValid($value)
    {
        if (!$value) return true;
        if (!is_array($value)) {
            $value = array($value);
        }
        foreach ($value as $key => $val) {
            if (strip_tags($val) != $val || stripos($val, 'Content-Type:') !== false) {
                $this->_error(self::INVALID_TAGS);
                return false;
            }
        }
        return true;
    }
}

Fix problems with validating null and integer values for tags


<?php

namespace spec\BackupManager\Filesystems;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class Awss3FilesystemSpec extends ObjectBehavior {

    function it_is_initializable() {
        $this->shouldHaveType('BackupManager\Filesystems\Awss3Filesystem');
    }

    function it_should_recognize_its_type_with_case_insensitivity() {
        foreach (['awss3', 'AWSS3', 'AwsS3'] as $type) {
            $this->handles($type)->shouldBe(true);
        }

        foreach ([null, 'foo'] as $type) {
            $this->handles($type)->shouldBe(false);
        }
    }

    function it_should_provide_an_instance_of_an_s3_filesystem() {
        $this->get($this->getConfig())->getAdapter()->shouldHaveType('League\Flysystem\AwsS3v3\AwsS3Adapter');
    }

    function getConfig() {
        return [
            'key'    => 'key',
            'secret' => 'secret',
            'region' => 0,
            'bucket' => 'bucket',
            'root'   => 'prefix',
            'version' => 'latest'
        ];
    }
}

<?php

namespace spec\BackupManager\Filesystems;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class Awss3FilesystemSpec extends ObjectBehavior {

    function it_is_initializable() {
        $this->shouldHaveType('BackupManager\Filesystems\Awss3Filesystem');
    }

    function it_should_recognize_its_type_with_case_insensitivity() {
        foreach (['awss3', 'AWSS3', 'AwsS3'] as $type) {
            $this->handles($type)->shouldBe(true);
        }

        foreach ([null, 'foo'] as $type) {
            $this->handles($type)->shouldBe(false);
        }
    }

    function it_should_provide_an_instance_of_an_s3_filesystem() {
        $this->get($this->getConfig())->getAdapter()->shouldHaveType('League\Flysystem\AwsS3v3\AwsS3Adapter');
    }

    function getConfig() {
        return [
            'key'    => 'key',
            'secret' => 'secret',
            'region' => 'us-east-1',
            'bucket' => 'bucket',
            'root'   => 'prefix',
            'version' => 'latest'
        ];
    }
}

Change integer to string for AWS S3 configuration in spec


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Milestone Celebration / Inc / Class
 */

namespace PH7;

use PH7\Framework\Core\Kernel;

final class MessageGenerator
{
    /**
     * @return string A random patron paragraph.
     */
    public static function getPatreonParagraph()
    {
        $aParagraphs = self::getParagraphs();

        return $aParagraphs[mt_rand(0, count($aParagraphs) - 1)];
    }

    /**
     * @return array
     */
    private static function getParagraphs()
    {
        $aParagraphs = [
            t('Do you think it is the right time to Become a Patron and support the development of the software?', Kernel::PATREON_URL),
            t('Are you generous enough to thank the development of the software? Become a patron today.', Kernel::PATREON_URL),
            t('Subscribe to pH7CMS Patreon.', Kernel::PATREON_URL),
            t('Subscribe to be a patron.', Kernel::PATREON_URL)
        ];

        return $aParagraphs;
    }
}

<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Milestone Celebration / Inc / Class
 */

namespace PH7;

use PH7\Framework\Core\Kernel;

final class MessageGenerator
{
    /**
     * @return string A random patron paragraph.
     */
    public static function getPatreonParagraph()
    {
        $aParagraphs = self::getParagraphs();

        return $aParagraphs[array_rand($aParagraphs)];
    }

    /**
     * @return array
     */
    private static function getParagraphs()
    {
        $aParagraphs = [
            t('Do you think it is the right time to Become a Patron and support the development of the software?', Kernel::PATREON_URL),
            t('Are you generous enough to thank the development of the software? Become a patron today.', Kernel::PATREON_URL),
            t('Subscribe to pH7CMS Patreon.', Kernel::PATREON_URL),
            t('Subscribe to be a patron.', Kernel::PATREON_URL)
        ];

        return $aParagraphs;
    }
}

Use `array_rand()` instead of `mt_rand()`/`count()` to reduce code, optimization, cleaner code


<?php

namespace BroadwaySerialization\Hydration;

/**
 * Simple implementation of a hydrator, which uses reflection to iterate over the properties of an object
 */
class HydrateUsingReflection implements Hydrate
{
    /**
     * @var array An array of arrays of \ReflectionProperty instances
     */
    private $properties = [];

    /**
     * @inheritdoc
     */
    public function hydrate(array $data, $object)
    {
        foreach ($this->propertiesOf($object) as $property) {
            if (!isset($data[$property->getName()])) {
                continue;
            }

            $property->setValue($object, $data[$property->getName()]);
        }
    }

    /**
     * @param object $object
     * @return \ReflectionProperty[]
     */
    private function propertiesOf($object)
    {
        $className = get_class($object);

        if (!isset($this->properties[$className])) {
            $this->properties[$className] = (new \ReflectionObject($object))->getProperties();
            foreach ($this->properties[$className] as $property) {
                /** @var \ReflectionProperty $property */
                $property->setAccessible(true);
            }
        }

        return $this->properties[$className];
    }
}

<?php

namespace BroadwaySerialization\Hydration;

/**
 * Simple implementation of a hydrator, which uses reflection to iterate over the properties of an object
 */
class HydrateUsingReflection implements Hydrate
{
    /**
     * @var array An array of arrays of \ReflectionProperty instances
     */
    private $properties = [];

    /**
     * @inheritdoc
     */
    public function hydrate(array $data, $object)
    {
        foreach ($this->propertiesOf($object) as $name => $property) {
            if (!isset($data[$name])) {
                continue;
            }

            $property->setValue($object, $data[$name]);
        }
    }

    /**
     * @param object $object
     * @return \ReflectionProperty[]
     */
    private function propertiesOf($object)
    {
        $className = get_class($object);

        if (!isset($this->properties[$className])) {
            foreach ((new \ReflectionObject($object))->getProperties() as $property) {
                /** @var \ReflectionProperty $property */
                $property->setAccessible(true);
                $this->properties[$className][$property->getName()] = $property;
            }
        }

        return $this->properties[$className];
    }
}

Reduce number of ReflectionProperty::getName calls


<?php

namespace OpenCFP\Test\Infrastructure\Persistence;

use OpenCFP\Infrastructure\Persistence\IlluminateAirportInformationDatabase;

/**
 * Tests integration with illuminate/database and airports table to implement
 * an AirportInfromationDatabase
 *
 * @group wip
 */
class IlluminateAirportInformationDatabaseTest extends \DatabaseTestCase
{
    private $airports;

    protected function setUp()
    {
        parent::setUp();

        $this->airports = $this->getAirportInformationDatabase();
    }

    /** @test */
    public function it_queries_airports_table_by_code()
    {
        $airport = $this->airports->withCode('RDU');

        $this->assertEquals('RDU', $airport->code);
        $this->assertEquals('Raleigh/Durham (NC)', $airport->name);
        $this->assertEquals('USA', $airport->country);
    }

    /** @test */
    public function it_squawks_when_airport_is_not_found()
    {
        $this->setExpectedException(\Exception::class, 'not found');

        $this->airports->withCode('foobarbaz');
    }

    /**
     * @return IlluminateAirportInformationDatabase
     */
    private function getAirportInformationDatabase()
    {
        return new IlluminateAirportInformationDatabase($this->getCapsule());
    }
}

<?php

namespace OpenCFP\Test\Infrastructure\Persistence;

use OpenCFP\Infrastructure\Persistence\IlluminateAirportInformationDatabase;

/**
 * Tests integration with illuminate/database and airports table to implement
 * an AirportInfromationDatabase
 */
class IlluminateAirportInformationDatabaseTest extends \DatabaseTestCase
{
    private $airports;

    protected function setUp()
    {
        parent::setUp();

        $this->airports = $this->getAirportInformationDatabase();
    }

    /** @test */
    public function it_queries_airports_table_by_code()
    {
        $airport = $this->airports->withCode('RDU');

        $this->assertEquals('RDU', $airport->code);
        $this->assertEquals('Raleigh/Durham (NC)', $airport->name);
        $this->assertEquals('USA', $airport->country);
    }

    /** @test */
    public function it_squawks_when_airport_is_not_found()
    {
        $this->setExpectedException(\Exception::class, 'not found');

        $this->airports->withCode('foobarbaz');
    }

    /**
     * @return IlluminateAirportInformationDatabase
     */
    private function getAirportInformationDatabase()
    {
        return new IlluminateAirportInformationDatabase($this->getCapsule());
    }
}

Remove spurious test group for work-in-progress


<?php

namespace Twitter;

use TwitterOAuth\TwitterOAuth as TwitterApi;

class LatestTweets
{
    /**
     *
     * @var TwitterApi
     */
    private $api;

    /**
     *
     * @param string $apiKey
     * @param string $apiSecret
     */
    public function __construct(TwitterApi $api)
    {
        $this->api = $api;
    }

    public function getLatestTweet($username)
    {
        $tweets = $this->getTweets($username, 1);

        return isset($tweets[0]) ? $tweets[0] : null;
    }

    public function getTweets($username, $howMany)
    {
        $tweets = $this->api->get('statuses/user_timeline', array(
            'screen_name' => $username,
            'exclude_replies' => 'true',
            'include_rts' => 'false',
            'count' => $howMany
        ));

        array_walk($tweets, function(&$tweet) {
            $tweet = new Tweet( (array) $tweet);
        });

        return $tweets;
    }
}

<?php

namespace Twitter;

use TwitterOAuth\TwitterOAuth as TwitterApi;

class LatestTweets
{
    /**
     *
     * @var TwitterApi
     */
    private $api;

    /**
     *
     * @param array $apiConfig
     */
    public function __construct(array $apiConfig)
    {
        $this->api = new TwitterApi($apiConfig);
    }

    public function getLatestTweet($username)
    {
        $tweets = $this->getTweets($username, 1);

        return isset($tweets[0]) ? $tweets[0] : null;
    }

    public function getTweets($username, $howMany)
    {
        $tweets = $this->api->get('statuses/user_timeline', array(
            'screen_name' => $username,
            'exclude_replies' => 'true',
            'include_rts' => 'false',
            'count' => $howMany
        ));

        array_walk($tweets, function(&$tweet) {
            $tweet = new Tweet( (array) $tweet);
        });

        return $tweets;
    }
}

Create instance of TwitterApi in constructor


<?php

namespace Rad\Logging\Adapter;

use Rad\Logging\AbstractAdapter;

/**
 * File Adapter
 *
 * @package Rad\Logging\Adapter
 */
class FileAdapter extends AbstractAdapter
{
    protected $handle;

    /**
     * Rad\Logging\Adapter\FileAdapter constructor
     *
     * @param string $filePath Log file path
     */
    public function __construct($filePath)
    {
        $this->handle = fopen($filePath, 'ab+');
    }

    /**
     * Rad\Logging\Adapter\FileAdapter destructor
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * Closes an open file pointer
     *
     * @return bool
     */
    public function close()
    {
        return fclose($this->handle);
    }

    /**
     * {@inheritdoc}
     */
    public function log($level, $message, $time, array $context = [])
    {
        fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context));
    }
}

<?php

namespace Rad\Logging\Adapter;

use Rad\Logging\AbstractAdapter;

/**
 * File Adapter
 *
 * @package Rad\Logging\Adapter
 */
class FileAdapter extends AbstractAdapter
{
    protected $handle;

    /**
     * Rad\Logging\Adapter\FileAdapter constructor
     *
     * @param string $filePath Log file path
     */
    public function __construct($filePath)
    {
        $dirPath = dirname($filePath);
        if (false === is_dir($dirPath)) {
            mkdir($dirPath, 0775, true);
        }

        if (substr($filePath, -4) !== '.log') {
            $filePath .= '.log';
        }

        $this->handle = fopen($filePath, 'ab+');
    }

    /**
     * Rad\Logging\Adapter\FileAdapter destructor
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * Closes an open file pointer
     *
     * @return bool
     */
    public function close()
    {
        return fclose($this->handle);
    }

    /**
     * {@inheritdoc}
     */
    public function log($level, $message, $time, array $context = [])
    {
        fwrite($this->handle, $this->getFormatter()->format($level, $message, $time, $context));
    }
}

Create log directory if does'nt exist.

Create log directory if does'nt exist.


<?php
namespace Concrete\Core\Application\UserInterface\Dashboard\Navigation;

use Symfony\Component\HttpFoundation\Session\Session;

abstract class AbstractNavigationCache
{

    abstract public function getIdentifier(): string;

    /**
     * @var Session
     */
    protected $session;

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

    public function has()
    {
        return $this->session->has($this->getIdentifier());
    }

    public function set(Navigation $navigation)
    {
        $this->session->set($this->getIdentifier(), $navigation);
    }

    public function get()
    {
        return $this->session->get($this->getIdentifier());
    }

    public function clear()
    {
        $this->session->remove($this->getIdentifier());
    }

}

<?php
namespace Concrete\Core\Application\UserInterface\Dashboard\Navigation;

use Concrete\Core\Localization\Localization;
use Symfony\Component\HttpFoundation\Session\Session;

abstract class AbstractNavigationCache
{

    abstract public function getIdentifier(): string;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var \Concrete\Core\Localization\Localization
     */
    protected $localization;

    public function __construct(Session $session, Localization $localization)
    {
        $this->session = $session;
        $this->localization = $localization;
    }

    public function has()
    {
        return $this->session->has($this->getSessionIdentifier());
    }

    public function set(Navigation $navigation)
    {
        $this->session->set($this->getSessionIdentifier(), $navigation);
    }

    public function get()
    {
        return $this->session->get($this->getSessionIdentifier());
    }

    public function clear()
    {
        $prefix = $this->getIdentifier() . '@';
        foreach (array_keys($this->session->all()) as $sessionKey) {
            if (strpos($sessionKey, $prefix) === 0) {
                $this->session->remove($sessionKey);
            }
        }
    }

    protected function getSessionIdentifier(): string
    {
        return $this->getIdentifier() . '@' . $this->localization->getLocale();
    }
}

Make the navigation cache localization-aware


<?php

/*
 * This file is part of the ACME PHP library.
 *
 * (c) Titouan Galopin <galopintitouan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AcmePhp\Ssl;

use Webmozart\Assert\Assert;

/**
 * Represent a Certificate.
 *
 * @author Jérémy Derussé <jeremy@derusse.com>
 */
class Certificate
{
    /** @var string */
    private $certificatePEM;

    /** @var Certificate */
    private $issuerCertificate;

    /**
     * @param string      $certificatePEM
     * @param Certificate $issuerCertificate
     */
    public function __construct($certificatePEM, Certificate $issuerCertificate = null)
    {
        Assert::stringNotEmpty($certificatePEM, __CLASS__.'::$certificatePEM should not be an empty string. Got %s');

        $this->certificatePEM = $certificatePEM;
        $this->issuerCertificate = $issuerCertificate;
    }

    /**
     * @return string
     */
    public function getPEM()
    {
        return $this->certificatePEM;
    }

    /**
     * @return Certificate
     */
    public function getIssuerCertificate()
    {
        return $this->issuerCertificate;
    }
}

<?php

/*
 * This file is part of the ACME PHP library.
 *
 * (c) Titouan Galopin <galopintitouan@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AcmePhp\Ssl;

use Webmozart\Assert\Assert;

/**
 * Represent a Certificate.
 *
 * @author Jérémy Derussé <jeremy@derusse.com>
 */
class Certificate
{
    /** @var string */
    private $certificatePEM;

    /** @var Certificate */
    private $issuerCertificate;

    /**
     * @param string      $certificatePEM
     * @param Certificate $issuerCertificate
     */
    public function __construct($certificatePEM, Certificate $issuerCertificate = null)
    {
        Assert::stringNotEmpty($certificatePEM, __CLASS__.'::$certificatePEM should not be an empty string. Got %s');

        $this->certificatePEM = $certificatePEM;
        $this->issuerCertificate = $issuerCertificate;
    }

    /**
     * @return Certificate[]
     */
    public function getIssuerChain()
    {
        $chain = [];
        $issuerCertificate = $this->getIssuerCertificate();

        while (null !== $issuerCertificate) {
            $chain[] = $issuerCertificate;
            $issuerCertificate = $issuerCertificate->getIssuerCertificate();
        }

        return $chain;
    }

    /**
     * @return string
     */
    public function getPEM()
    {
        return $this->certificatePEM;
    }

    /**
     * @return Certificate
     */
    public function getIssuerCertificate()
    {
        return $this->issuerCertificate;
    }
}

Implement Push to Rancher post-generate action


<?php

namespace ResponsiveImages;

use Functional as F;

/**
 * Class Slot
 */
class Slot
{
  /**
   * @var Size[]
   */
  private $sizes = [];

  /**
   * @var Source[]
   */
  private $sources = [];

  function __construct(array $sizes)
  {
    $this->sizes = $sizes;
    $this->groupSizesIntoSources();
  }

  private function groupSizesIntoSources()
  {
    $prev_aspect_ratio = null;
    $source = [];
    foreach ($this->sizes as $size) {
      $aspect_ratio = $size->getAspectRatio();
      if (isset($prev_aspect_ratio) and $aspect_ratio !== $prev_aspect_ratio) {
        $this->sources[] = new Source($source);
        $source = [];
      }
      $prev_aspect_ratio = $aspect_ratio;
      $source[] = $size;
    }
    $sources[] = new Source($source, true);
  }

  public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
  {
    if (count($this->sources) === 1)
      return $this->sources[0]->renderFor($uri);

    $html = F\reduce_left($this->sources,
      function(Source $source, $i, $c, $acc) use ($uri, $srcset_gen){
        return "$acc\n  ".$source->renderFor($uri, $srcset_gen);
      }, '');

    return "<picture>$html\n</picture>";
  }
}

<?php

namespace ResponsiveImages;

use Functional as F;

/**
 * Class Slot
 */
class Slot
{
  /**
   * @var Size[]
   */
  private $sizes = [];

  /**
   * @var Source[]
   */
  private $sources = [];

  function __construct(array $sizes)
  {
    $this->sizes = $sizes;
    $this->groupSizesIntoSources();
  }

  private function groupSizesIntoSources()
  {
    $prev_aspect_ratio = null;
    $source = [];
    foreach ($this->sizes as $size) {
      $aspect_ratio = $size->getAspectRatio();
      if (isset($prev_aspect_ratio) and $aspect_ratio !== $prev_aspect_ratio) {
        $this->sources[] = new Source($source);
        $source = [];
      }
      $prev_aspect_ratio = $aspect_ratio;
      $source[] = $size;
    }
    $this->sources[] = new Source($source, true);
  }

  public function renderFor($uri, SrcsetGeneratorInterface $srcset_gen)
  {
    if (count($this->sources) === 1)
      return $this->sources[0]->renderFor($uri);

    $html = F\reduce_left($this->sources,
      function(Source $source, $i, $c, $acc) use ($uri, $srcset_gen){
        return "$acc\n  ".$source->renderFor($uri, $srcset_gen);
      }, '');

    return "<picture>$html\n</picture>";
  }
}

Fix <img> not being printed to <picture>.


<?php

namespace Funstaff\FeedBundle\Factory;

/**
 * Factory
 *
 * @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
 */
class Factory
{
    protected $config;

    static protected $versions = array(
        '091', '092', '201', 'atom'
    );

    /**
     * Construct
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;
    }

    /**
     * Create Feed
     *
     * @param string $name
     * @param string $version
     *
     * @param feed
     */
    public function createFeed($name, $version = '201')
    {
        if (!array_key_exists($name, $this->config['channels'])) {
            throw new \InvalidArguementException('Invalid channel.');
        }

        if (!in_array($version, self::$versions)) {
            throw new \InvalidArgumentException('Invalid feed version.');
        }

        $class = sprintf('feed%s', ucfirst($version));
        $feed = $this->config['classes'][$class];

        return new $feed();
    }
}

<?php

namespace Funstaff\FeedBundle\Factory;

/**
 * Factory
 *
 * @author Bertrand Zuchuat <bertrand.zuchuat@gmail.com>
 */
class Factory
{
    protected $config;

    static protected $versions = array(
        '091', '092', '201', 'atom'
    );

    /**
     * Construct
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->config = $config;
    }

    /**
     * Create Feed
     *
     * @param string $name
     * @param string $version
     *
     * @param feed
     */
    public function createFeed($name, $version = '201')
    {
        if (!array_key_exists($name, $this->config['channels'])) {
            throw new \InvalidArguementException('Invalid channel.');
        }

        if (!in_array($version, self::$versions)) {
            throw new \InvalidArgumentException('Invalid feed version.');
        }

        $class = sprintf('feed%s', ucfirst($version));
        if (!array_key_exists($class, $this->config['classes'])) {
            throw new \InvalidArgumentException('Invalid feed class');
        }
        $feed = $this->config['classes'][$class];

        return new $feed($this->config['channels'][$name]);
    }
}

Add test on feed class

Add test on feed class


<?php
class Kwf_Assets_Util_Trl
{
    //returns replacement used for js trl strings
    //used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
    public static function getJsReplacement($trlElement)
    {
        $b = $trlElement['before'];
        $fn = substr($b, 0, strpos($b, '('));
        $key = $trlElement['type'].'.'.$trlElement['source'];
        if (isset($trlElement['context'])) $key .= '.'.$trlElement['context'];
        $key .= '.'.str_replace("'", "\\'", $trlElement['text']);
        $replace = '';
        if (preg_match('#^([a-z]+\.)trl#i', $b, $m)) {
            $replace = substr($b, 0, strlen($m[1]));
        }
        if ($trlElement['type'] == 'trlp' || $trlElement['type'] == 'trlcp') {
            $replace .= "_kwfTrlp";
        } else {
            $replace .= "_kwfTrl";
        }
        $replace .= "('$key', ".substr($b, strpos($b, '(')+1);

        unset($trlElement['before']);
        unset($trlElement['linenr']);
        unset($trlElement['error_short']);

        return array(
            'before' => $b,
            'replace' => $replace,
            'trlElement' => (object)$trlElement
        );
    }
}

<?php
class Kwf_Assets_Util_Trl
{
    //returns replacement used for js trl strings
    //used by Kwf_Assets_Dependency_File_Js and Kwf_Assets_CommonJs_Underscore_TemplateDependency
    public static function getJsReplacement($trlElement)
    {
        $b = $trlElement['before'];
        $fn = substr($b, 0, strpos($b, '('));
        $key = $trlElement['type'].'.'.$trlElement['source'];
        if (isset($trlElement['context'])) $key .= '.'.$trlElement['context'];
        $key .= '.'.str_replace("'", "\\'", $trlElement['text']);
        $replace = '';
        if (preg_match('#^(_?([a-z]+(2\.default)?\.))trl#i', $b, $m)) {
            $replace = substr($b, 0, strlen($m[1]));
        }
        if ($trlElement['type'] == 'trlp' || $trlElement['type'] == 'trlcp') {
            $replace .= "_kwfTrlp";
        } else {
            $replace .= "_kwfTrl";
        }
        $replace .= "('$key', ".substr($b, strpos($b, '(')+1);

        unset($trlElement['before']);
        unset($trlElement['linenr']);
        unset($trlElement['error_short']);

        return array(
            'before' => $b,
            'replace' => $replace,
            'trlElement' => (object)$trlElement
        );
    }
}

Improve regexp to match result from babel

Babel does convert commonjs require calls from
var bar = require('bar');
bar.foo('test');
into
 _bar2.default.foo('test')
therefore this regexp need to consider _ and 2.default as optional


<?php

#sleep(2);

$feed = new sspmod_discojuice_Feed();

if (!empty($_REQUEST['refresh'])) {
	$feed->store();
	$data = $feed->read();
} else {
	$data = $feed->read();
}

if (!empty($_REQUEST['debug'])) {

	header('Content-Type: text/plain; charset=utf-8');
	print_r($data);

}

header('Content-Type: application/json; charset=utf-8');

if(isset($_REQUEST['callback'])) {
	echo $_REQUEST['callback'] . '(' . $data . ');';
} else {
	echo $data;
}

<?php

#sleep(2);

$feed = new sspmod_discojuice_Feed();

if (!empty($_REQUEST['refresh'])) {
	$feed->store();
	$data = $feed->read();
} else {
	$data = $feed->read();
}

if (!empty($_REQUEST['debug'])) {

	header('Content-Type: text/plain; charset=utf-8');
	print_r(json_decode($data, 'utf-8'));
	exit;
}

header('Content-Type: application/json; charset=utf-8');

if(isset($_REQUEST['callback'])) {
	echo $_REQUEST['callback'] . '(' . $data . ');';
} else {
	echo $data;
}

Improve DiscoJuice Feed debug view

Improve DiscoJuice Feed debug view


<?php

namespace PhpSchool\PhpWorkshop\Check;

use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface;
use PhpSchool\PhpWorkshop\Result\ResultInterface;

/**
 * Class CheckInterface
 * @package PhpSchool\PhpWorkshop\Comparator
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */
interface CheckInterface
{
    /**
     * @param ExerciseInterface $exercise
     * @param string $fileName
     * @return ResultInterface
     */
    public function check(ExerciseInterface $exercise, $fileName);

    /**
     * Return the check's name
     *
     * @return string
     */
    public function getName();
}

<?php

namespace PhpSchool\PhpWorkshop\Check;

use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface;
use PhpSchool\PhpWorkshop\Result\ResultInterface;

/**
 * Class CheckInterface
 * @package PhpSchool\PhpWorkshop\Comparator
 * @author Aydin Hassan <aydin@hotmail.co.uk>
 */
interface CheckInterface
{
    /**
     * @param ExerciseInterface $exercise
     * @param string $fileName
     * @return ResultInterface
     */
    public function check(ExerciseInterface $exercise, $fileName);

    /**
     * Return the check's name
     *
     * @return string
     */
    public function getName();

    /**
     * Which Exercise Type this
     * checks applies to
     * @see \PhpSchool\PhpWorkshop\Exercise\ExerciseType
     *
     * @return ExerciseType
     */
    public function appliesTo();

    /**
     * This returns the interface the exercise should implement
     * when requiring this check
     *
     * @return string
     */
    public function getExerciseInterface();
}

Add additional methods for the exercise type and interface


<?php

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

class CreateArticleAggregatedViewsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article_aggregated_views', function (Blueprint $table) {
            $table->integer('article_id')->unsigned();
            $table->string('user_id')->nullable();
            $table->string('browser_id');
            $table->date('date');
            $table->integer('pageviews')->default(0);
            $table->integer('timespent')->default(0);

            $table->primary(['article_id', 'user_id', 'browser_id', 'date'], 'primary_index');
            $table->foreign('article_id')->references('id')->on('articles');
        });
    }

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

<?php

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

class CreateArticleAggregatedViewsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article_aggregated_views', function (Blueprint $table) {
            $table->integer('article_id')->unsigned();
            $table->string('user_id');
            $table->string('browser_id');
            $table->date('date');
            $table->integer('pageviews')->default(0);
            $table->integer('timespent')->default(0);

            $table->primary(['article_id', 'user_id', 'browser_id', 'date'], 'primary_index');
            $table->foreign('article_id')->references('id')->on('articles');
        });
    }

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

Make article_aggregated_views user_id column non-nullable


<?php

namespace Coreplex\Meta\Eloquent;

use Coreplex\Meta\Contracts\Variant;

trait HasMetaData
{
    /**
     * Retrieve the meta data for this model
     *
     * @param Variant $variant
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function meta(Variant $variant = null)
    {
        if ( ! $variant) {
            return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
        }

        return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
                    ->where('variant_id', $variant->getKey())
                    ->where('variant_type', $variant->getType());
    }

    /**
     * Check if the meta has been set for the metable item, if a variant is
     * passed then check if it is set for the variant.
     *
     * @param Variant|null $variant
     * @return bool
     */
    public function hasMeta(Variant $variant = null)
    {
        return $this->meta($variant)->exists();
    }

    /**
     * Get the meta data for the metable item.
     *
     * @param Variant|null $variant
     * @return mixed
     */
    public function getMeta(Variant $variant = null)
    {
        if ($variant) {
            return $this->meta($variant)->getResults();
        }

        return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
    }
}

<?php

namespace Coreplex\Meta\Eloquent;

use Coreplex\Meta\Contracts\Variant;

trait HasMetaData
{
    /**
     * Retrieve the meta data for this model
     *
     * @param Variant $variant
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
     */
    public function meta(Variant $variant = null)
    {
        if ( ! $variant) {
            return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable');
        }

        return $this->morphOne('Coreplex\Meta\Eloquent\Meta', 'metable')
                    ->where('variant_id', $variant->getKey())
                    ->where('variant_type', $variant->getType());
    }

    /**
     * Check if the meta has been set for the metable item, if a variant is
     * passed then check if it is set for the variant.
     *
     * @param Variant|null $variant
     * @return bool
     */
    public function hasMeta(Variant $variant = null)
    {
        if (! empty($variant)) {
            return $this->meta($variant)->exists();
        }

        $this->meta()->whereNull('variant_type')->whereNull('variant_id')->exists();
    }

    /**
     * Get the meta data for the metable item.
     *
     * @param Variant|null $variant
     * @return mixed
     */
    public function getMeta(Variant $variant = null)
    {
        if ($variant) {
            return $this->meta($variant)->getResults();
        }

        return $this->meta()->whereNull('variant_type')->whereNull('variant_id')->getResults();
    }
}

Fix issue with has meta to match get meta


<?php
/*
 * Classic theme
 * Author: Jonathan Kim
 * Date: 30/12/2011
 */

use FelixOnline\Core;

if(!defined('THEME_DIRECTORY')) define('THEME_DIRECTORY', dirname(__FILE__));
if(!defined('THEME_NAME')) define('THEME_NAME', '2014');
if(!defined('THEME_URL')) define('THEME_URL', STANDARD_URL.'themes/'.THEME_NAME.'/');

global $hooks;

/*
 * Load in theme specific functions
 */
require_once(THEME_DIRECTORY.'/core/functions.php');

/*
 * Set default site wide resources
 */
$this->resources = new Core\ResourceManager(
	/* CSS files */
	array('foundation.css', 'felix.css', '../slick/slick.css'),
	/* JS files */
	array('vendor/jquery.js', 'foundation.min.js', 'foundation/foundation.reveal.js', '../slick/slick.js', 'script.js')
);

?>

<?php
/*
 * Classic theme
 * Author: Jonathan Kim
 * Date: 30/12/2011
 */

use FelixOnline\Core;

if(!defined('THEME_DIRECTORY')) define('THEME_DIRECTORY', dirname(__FILE__));
if(!defined('THEME_NAME')) define('THEME_NAME', '2014');
if(!defined('THEME_URL')) define('THEME_URL', STANDARD_URL.'themes/'.THEME_NAME.'/');

global $hooks;

/*
 * Load in theme specific functions
 */
require_once(THEME_DIRECTORY.'/core/functions.php');

/*
 * Set default site wide resources
 */
$this->resources = new Core\ResourceManager(
	/* CSS files */
	array('foundation.css', 'felix.css', '../slick/slick.css', 'rrssb.css'),
	/* JS files */
	array('vendor/jquery.js', 'foundation.min.js', 'foundation/foundation.reveal.js', '../slick/slick.js', 'script.js', 'rrssb.min.js')
);

?>

Add responsive sharer to resources

Add responsive sharer to resources


<?php
/**
 * Toast messages file.
 * This file is being included in footer_scripts.php
 *
 * Shows toasts for the various 'levels':
 * - notice
 * - success
 * - warning
 * - error
 *
 * Success toasts are the only ones not sticky due to its nature.
 */
?>
<?php $messages = Status_msg::get(); ?>
<?php if ($messages) : ?>
  <script>
  <?php foreach($messages as $index => $msg): ?>
  $().toastmessage('showToast', {
    sticky   : <?= $msg['sticky'] ? 'true' : 'false'; ?>,
    text     : '<?= $msg['msg']; ?>',
    type     : '<?= $msg['level']; ?>',
    inEffectDuration : 100,
    position : 'bottom-right',
  });
  <?php endforeach; ?>
  </script>
<?php endif; ?>

<?php
/**
 * Toast messages file.
 * This file is being included in footer_scripts.php
 *
 * Shows toasts for the various 'levels':
 * - notice
 * - success
 * - warning
 * - error
 *
 * Success toasts are the only ones not sticky due to its nature.
 */
?>
<?php $messages = Status_msg::get(); ?>
<?php if ($messages) : ?>
  <script>
  <?php foreach($messages as $index => $msg): ?>
  $().toastmessage('showToast', {
    sticky   : <?= $msg['sticky'] ? 'true' : 'false'; ?>,
    text     : "<?= $msg['msg']; ?>",
    type     : '<?= $msg['level']; ?>',
    inEffectDuration : 100,
    position : 'bottom-right',
  });
  <?php endforeach; ?>
  </script>
<?php endif; ?>

Fix toast problem with apostrophe

Fix toast problem with apostrophe


<?php

namespace Speicher210\KontaktIO;

use function GuzzleHttp\default_user_agent;

class Client extends \GuzzleHttp\Client
{
    const API_VERSION_STABLE = '7';

    const API_VERSION_LATEST = '8';

    /**
     * Constructor.
     *
     * @param string $apiKey
     * @param string $version
     */
    public function __construct($apiKey, $version = self::API_VERSION_STABLE)
    {
        parent::__construct(
            [
                'base_uri' => 'https://api.kontakt.io',
                'headers' => [
                    'Accept' => 'application/vnd.com.kontakt+json;version=' . $version,
                    'Api-Key' => $apiKey,
                    'User-Agent' => 'Speicher210/KontaktIO ' . default_user_agent(),
                ],
            ]
        );
    }
}

<?php

declare(strict_types = 1);

namespace Speicher210\KontaktIO;

use function GuzzleHttp\default_user_agent;

class Client extends \GuzzleHttp\Client
{
    public const API_VERSION_STABLE = '9';

    public const API_VERSION_LATEST = '10';

    /**
     * @param string $apiKey
     * @param string $version
     */
    public function __construct($apiKey, $version = self::API_VERSION_STABLE)
    {
        parent::__construct(
            [
                'base_uri' => 'https://api.kontakt.io',
                'headers' => [
                    'Accept' => 'application/vnd.com.kontakt+json;version=' . $version,
                    'Api-Key' => $apiKey,
                    'User-Agent' => 'Speicher210/KontaktIO ' . default_user_agent()
                ]
            ]
        );
    }
}

Update the API version used

Update the API version used


<?php

namespace Rezzza\Jobflow\Extension\ETL\Processor;

use Knp\ETL\ContextInterface;
use Knp\ETL\TransformerInterface;
use Psr\Log\LoggerInterface;
use Rezzza\Jobflow\Metadata\MetadataAccessor;
use Rezzza\Jobflow\Processor\JobProcessor;
use Rezzza\Jobflow\Scheduler\ExecutionContext;

class TransformerProxy extends ETLProcessor implements TransformerInterface, JobProcessor
{
    public function __construct(TransformerInterface $processor, MetadataAccessor $metadataAccessor, LoggerInterface $logger = null)
    {
        // Construct used for TypeHinting
        parent::__construct($processor, $metadataAccessor, $logger);
    }

    public function transform($data, ContextInterface $context)
    {
        return $this->processor->transform($data, $context);
    }

    public function execute(ExecutionContext $execution)
    {
        $data = $execution->read();

        $this->debug(count($data) .' rows');

        foreach ($data as $k => $result) {
            $value = $result->getValue();
            $metadata = $result->getMetadata();
            $context = $this->createContext($execution, $metadata);

            $transformedData = $this->transform($value, $context);

            $metadata = $this->metadataAccessor->createMetadata($value, $metadata);

            $execution->write($transformedData, $metadata);
        }

        $execution->valid();
    }
}

<?php

namespace Rezzza\Jobflow\Extension\ETL\Processor;

use Knp\ETL\ContextInterface;
use Knp\ETL\TransformerInterface;
use Psr\Log\LoggerInterface;
use Rezzza\Jobflow\Metadata\MetadataAccessor;
use Rezzza\Jobflow\Processor\JobProcessor;
use Rezzza\Jobflow\Scheduler\ExecutionContext;

class TransformerProxy extends ETLProcessor implements TransformerInterface, JobProcessor
{
    public function __construct(TransformerInterface $processor, MetadataAccessor $metadataAccessor, LoggerInterface $logger = null)
    {
        // Construct used for TypeHinting
        parent::__construct($processor, $metadataAccessor, $logger);
    }

    public function transform($data, ContextInterface $context)
    {
        return $this->processor->transform($data, $context);
    }

    public function execute(ExecutionContext $execution)
    {
        $data = $execution->read();

        $this->debug(count($data) .' rows');

        foreach ($data as $k => $result) {
            $value = $result->getValue();
            $metadata = $result->getMetadata();
            $context = $this->createContext($execution, $metadata);

            $transformedData = $this->transform($value, $context);

            if (is_array($transformedData)) {
                foreach ($transformedData as $d) {
                    $this->writeData($value, $metadata, $execution, $d);
                }
            } else {
                $this->writeData($value, $metadata, $execution, $transformedData);
            }
        }

        $execution->valid();
    }

    private function writeData($value, $metadata, $execution, $data)
    {
        $metadata = $this->metadataAccessor->createMetadata($value, $metadata);
        $execution->write($data, $metadata);
    }
}

Deal with transformer with retuns array

Deal with transformer with retuns array


<?php

declare (strict_types=1);

namespace DragonBe\Test\Vies\Validator;

class ValidatorBGTest extends AbstractValidatorTest
{
    /**
     * @covers \DragonBe\Vies\Validator\ValidatorBG
     * @dataProvider vatNumberProvider
     */
    public function testValidator(string $vatNumber, bool $state)
    {
        $this->validateVatNumber('BG', $vatNumber, $state);
    }

    public function vatNumberProvider()
    {
        return [
            ['301004503', true],
            ['10100450', false],
            ['301004502', false],
            ['8311046307', true],
        ];
    }
}

<?php

declare (strict_types=1);

namespace DragonBe\Test\Vies\Validator;

class ValidatorBGTest extends AbstractValidatorTest
{
    /**
     * @covers \DragonBe\Vies\Validator\ValidatorBG
     * @dataProvider vatNumberProvider
     */
    public function testValidator(string $vatNumber, bool $state)
    {
        $this->validateVatNumber('BG', $vatNumber, $state);
    }

    public function vatNumberProvider()
    {
        return [
            ['301004503', true],
            ['10100450', false],
            ['301004502', false],
            ['8311046307', true],
            ['3002779909', true],
        ];
    }
}

Add new BG test case for foreign natural persons


<?php
namespace Camspiers\StatisticalClassifier\DataSource;

/**
 * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-03-26 at 18:06:09.
 */
class GroupedTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
    }

    /**
     * @covers Camspiers\StatisticalClassifier\DataSource\Grouped::addDataSource
     * @todo   Implement testAddDataSource().
     */
    public function testAddDataSource()
    {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
          'This test has not been implemented yet.'
        );
    }

    /**
     * @covers Camspiers\StatisticalClassifier\DataSource\Grouped::read
     * @todo   Implement testRead().
     */
    public function testRead()
    {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
          'This test has not been implemented yet.'
        );
    }
}

<?php

namespace Camspiers\StatisticalClassifier\DataSource;

class GroupedTest extends \PHPUnit_Framework_TestCase
{
    public function testObjectCreateViaArray()
    {
        $sources = array(
            $this->getMock(__NAMESPACE__ . '\\' . 'DataSourceInterface'),
            $this->getMock(__NAMESPACE__ . '\\' . 'DataSourceInterface')
        );

        $object = new Grouped($sources);

        $this->assertInstanceOf(__NAMESPACE__ . '\\' . 'Grouped', $object);

        $this->assertEquals(2, count($object->getDataSources()));
    }

    public function testObjectCreateViaDynamicArgs()
    {
        $object = new Grouped(
            $this->getMock(__NAMESPACE__ . '\\' . 'DataSourceInterface'),
            $this->getMock(__NAMESPACE__ . '\\' . 'DataSourceInterface')
        );

        $this->assertInstanceOf(__NAMESPACE__ . '\\' . 'Grouped', $object);

        $this->assertEquals(2, count($object->getDataSources()));
    }

    public function testRead()
    {
        $source1 = $this->getMock(__NAMESPACE__ . '\\' . 'DataSourceInterface');
        $source1->expects($this->once())->method('getData')->will($this->returnValue(array(
            array(
                'document' => 'Hello',
                'category' => 'super'
            )
        )));
        $source2 = $this->getMock(__NAMESPACE__ . '\\' . 'DataSourceInterface');
        $source2->expects($this->once())->method('getData')->will($this->returnValue(array(
            array(
                'document' => 'Hello',
                'category' => 'super'
            )
        )));

        $object = new Grouped($source1, $source2);

        $this->assertEquals(
            array(
                array(
                    'document' => 'Hello',
                    'category' => 'super'
                ),
                array(
                    'document' => 'Hello',
                    'category' => 'super'
                )
            ),
            $object->read()
        );
    }
}

Add test for Grouped datasource

Add test for Grouped datasource


<?php

final class PhabricatorCalendarEventAllDayTransaction
  extends PhabricatorCalendarEventTransactionType {

  const TRANSACTIONTYPE = 'calendar.allday';

  public function generateOldValue($object) {
    return (int)$object->getIsAllDay();
  }

  public function generateNewValue($object, $value) {
    return (int)$value;
  }

  public function applyInternalEffects($object, $value) {
    $object->setIsAllDay($value);
  }

  public function getTitle() {
    if ($this->getNewValue()) {
      return pht(
        '%s changed this as an all day event.',
        $this->renderAuthor());
    } else {
      return pht(
        '%s conveted this from an all day event.',
        $this->renderAuthor());
    }
  }

  public function getTitleForFeed() {
    if ($this->getNewValue()) {
      return pht(
        '%s changed %s to an all day event.',
        $this->renderAuthor(),
        $this->renderObject());
    } else {
      return pht(
        '%s converted %s from an all day event.',
        $this->renderAuthor(),
        $this->renderObject());
    }
  }

}

<?php

final class PhabricatorCalendarEventAllDayTransaction
  extends PhabricatorCalendarEventTransactionType {

  const TRANSACTIONTYPE = 'calendar.allday';

  public function generateOldValue($object) {
    return (int)$object->getIsAllDay();
  }

  public function generateNewValue($object, $value) {
    return (int)$value;
  }

  public function applyInternalEffects($object, $value) {
    $object->setIsAllDay($value);
  }

  public function getTitle() {
    if ($this->getNewValue()) {
      return pht(
        '%s changed this as an all day event.',
        $this->renderAuthor());
    } else {
      return pht(
        '%s converted this from an all day event.',
        $this->renderAuthor());
    }
  }

  public function getTitleForFeed() {
    if ($this->getNewValue()) {
      return pht(
        '%s changed %s to an all day event.',
        $this->renderAuthor(),
        $this->renderObject());
    } else {
      return pht(
        '%s converted %s from an all day event.',
        $this->renderAuthor(),
        $this->renderObject());
    }
  }

}

Fix typo at calendar transaction

Fix typo at calendar transaction

Summary:
* Fixed conveted => converted
Ref T11576

Test Plan: * Looked at a page, where somebody converted an AllDay Event to a normal one

Reviewers: #blessed_reviewers, epriestley

Reviewed By: #blessed_reviewers, epriestley

Subscribers: epriestley

Tags: #calendar

Maniphest Tasks: T11576

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


<?php

namespace makeandship\elasticsearch\transformer;

use makeandship\elasticsearch\Util;

class SearchTransformer
{
    public function transform($response)
    {
        $val = array(
            'total' => $response->getTotalHits(),
            'facets' => array(),
            'ids' => array(),
            'results' => array()
        );

        foreach ($response->getAggregations() as $name => $agg) {
            if (isset($agg['facet']['buckets'])) {
                foreach ($agg['facet']['buckets'] as $bucket) {
                    $val['facets'][$name][$bucket['key']] = $bucket['doc_count'];
                }
            }

            if (isset($agg['range']['buckets'])) {
                foreach ($agg['range']['buckets'] as $bucket) {
                    $from = isset($bucket['from']) ? $bucket['from'] : '';
                    $to = isset($bucket['to']) && $bucket['to'] != '*' ? $bucket['to'] : '';

                    $val['facets'][$name][$from . '-' . $to] = $bucket['doc_count'];
                }
            }
        }

        foreach ($response->getResults() as $result) {
            $id = $result->getId();
            $source = $result->getSource();
            $source['id'] = $id;

            $highlight = Util::safely_get_attribute($result, 'highlight');
            if ($highlight) {
                $source['highlight'] = $highlight;
            }

            $val['ids'][] = $id;
            $val['results'][] = $source;
        }

        return Util::apply_filters('searcher_results', $val, $response);
    }
}

<?php

namespace makeandship\elasticsearch\transformer;

use makeandship\elasticsearch\Util;

class SearchTransformer
{
    public function transform($response)
    {
        $val = array(
            'total' => $response->getTotalHits(),
            'facets' => array(),
            'ids' => array(),
            'results' => array()
        );

        foreach ($response->getAggregations() as $name => $agg) {
            if (isset($agg['facet']['buckets'])) {
                foreach ($agg['facet']['buckets'] as $bucket) {
                    $val['facets'][$name][$bucket['key']] = $bucket['doc_count'];
                }
            }

            if (isset($agg['range']['buckets'])) {
                foreach ($agg['range']['buckets'] as $bucket) {
                    $from = isset($bucket['from']) ? $bucket['from'] : '';
                    $to = isset($bucket['to']) && $bucket['to'] != '*' ? $bucket['to'] : '';

                    $val['facets'][$name][$from . '-' . $to] = $bucket['doc_count'];
                }
            }
        }

        foreach ($response->getResults() as $result) {
            $id = $result->getId();
            $source = $result->getSource();
            $hit = $result->getHit();
            $source['id'] = $id;

            $highlight = Util::safely_get_attribute($hit, 'highlight');
            if ($highlight) {
                $source['highlight'] = $highlight;
            }

            $val['ids'][] = $id;
            $val['results'][] = $source;
        }

        return Util::apply_filters('searcher_results', $val, $response);
    }
}

Add highlight to result in transformer

Add highlight to result in transformer