<?php
require_once 'TextCat.php';

if($argc != 3) {
	die("Use $argv[0] INPUTDIR OUTPUTDIR\n");
}
if(!file_exists($argv[2])) {
	mkdir($argv[2], 0755, true);
}
$cat = new TextCat($argv[2]);

foreach(new DirectoryIterator($argv[1]) as $file) {
	if(!$file->isFile()) {
		continue;
	}
	$ngrams = array();
	foreach(file($file->getPathname(), FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES) as $line) {
		list($word, $score) = explode("\t ", $line, 2);
		$ngrams[$word] = intval($score);
	}
	$cat->writeLanguageFile($ngrams, $argv[2] . "/" . $file->getBasename());
}
exit(0);

Add converter from old tool's format to PHP format


<?php

/*
 * This file is part of the JsonSchema package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace JsonSchema\Tests\Constraints;

use JsonSchema\Constraints\Type;

/**
 * Class TypeTest
 *
 * @package JsonSchema\Tests\Constraints
 * @author hakre <https://github.com/hakre>
 */
class TypeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @see testIndefiniteArticleForTypeInTypeCheckErrorMessage
     * @return array
     */
    public function provideIndefiniteArticlesForTypes()
    {
        return array(
            array('integer', 'an',),
            array('number', 'a',),
            array('boolean', 'a',),
            array('object', 'an',),
            array('array', 'an',),
            array('string', 'a',),
            array('null', 'a', array(), 'array',),
        );
    }

    /**
     * @dataProvider provideIndefiniteArticlesForTypes
     */
    public function testIndefiniteArticleForTypeInTypeCheckErrorMessage($type, $wording, $value = null, $label = 'NULL')
    {
        $constraint = new Type();
        $constraint->check($value, (object)array('type' => $type));
        $this->assertTypeConstraintError("$label value found, but $wording $type is required", $constraint);
    }

    /**
     * Helper to assert an error message
     *
     * @param string $expected
     * @param Type $actual
     */
    private function assertTypeConstraintError($expected, Type $actual)
    {
        $actualErrors = $actual->getErrors();

        $this->assertCount(1, $actualErrors, "Failed to assert that Type has exactly one error to assert the error message against.");

        $actualError = $actualErrors[0];

        $this->assertInternalType('array', $actualError, sprintf('Failed to assert that Type error is an array, %s given', gettype($actualError)));

        $messageKey = 'message';
        $this->assertArrayHasKey(
            $messageKey, $actualError,
            sprintf('Failed to assert that Type error has a message key %s.', var_export($messageKey, true))
        );

        $actualMessage = $actualError[$messageKey];

        $this->assertEquals($expected, $actualMessage); // first equal for the diff
        $this->assertSame($expected, $actualMessage); // the same for the strictness
    }
}

Add test-case for Type error messages

Add test-case for Type error messages


<?php
/**
 * This will hide subscription levels on the registration form page
 * if their price is lower than the price of member's current
 * subscription level.
 */
function jp_hide_lower_cost_levels( $levels ) {

	if ( ! rcp_is_registration_page() || ! is_user_logged_in() ) {
		return $levels;
	}

	$existing_sub = rcp_get_subscription_id( wp_get_current_user()->ID );

	if ( empty( $existing_sub ) ) {
		return $levels;
	}

	foreach( $levels as $key => $level ) {
		if ( rcp_get_subscription_price( $level->id ) < rcp_get_subscription_price( $existing_sub ) ) {
			unset( $levels[$key] );
		}
	}

	return $levels;
}
add_filter( 'rcp_get_levels', 'jp_hide_lower_cost_levels' );

Hide lower priced subscription levels on the registration form for existing members.


<?php

class Denkmal_Paging_Link_AllTest extends CMTest_TestCase {

    public function tearDown() {
        CMTest_TH::clearEnv();
    }

    public function testGetItems() {
        $link1 = Denkmal_Model_Link::create('foo', 'http://foo.com', true);
        $link2 = Denkmal_Model_Link::create('bar', 'http://bar.com', false);

        $paging = new Denkmal_Paging_Link_All();
        $this->assertEquals(array($link2, $link1), $paging->getItems());

        $link2->delete();
        $paging = new Denkmal_Paging_Link_All();
        $this->assertEquals(array($link1), $paging->getItems());
    }
}

Add test for all linklist

Add test for all linklist


<?php

namespace Onesky\Api\Tests;

use Onesky\Api\Client;

/**
 * Class to test the translations resource.
 *
 * See more about translations resource here:
 * https://github.com/onesky/api-documentation-platform/blob/master/resources/translation.md
 *
 * @author Bernardo Silva <benny.stuff@gmail.com>
 */
class TranslationsApiTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Onesky\Api\Client $api */
    protected $api;

    public function setUp()
    {
        $this->api = new Client();
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Invalid resource action
     */
    public function testTranslationsDetectMissingResourceAction()
    {
        $this->api->translations();
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Missing parameter: project_id
     */
    public function testTranslationsExportDetectMissingParam()
    {
        $this->api->translations('export');
    }

    /**
     * @expectedException \UnexpectedValueException
     * @expectedExceptionMessage Invalid authenticate data of api key or secret
     */
    public function testTranslationsExportDetectInvalidAuthentication()
    {
        $this->api->translations('export', ['project_id' => 123]);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Missing parameter: project_id
     */
    public function testTranslationsStatusDetectMissingParam()
    {
        $this->api->translations('status');
    }

    /**
     * @expectedException \UnexpectedValueException
     * @expectedExceptionMessage Invalid authenticate data of api key or secret
     */
    public function testTranslationsStatusDetectInvalidAuthentication()
    {
        $this->api->translations('status', ['project_id' => 123]);
    }

}

Add base tests for translations resource.


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
namespace Zend\Form\Element\FileTest\Adapter;

/**
 * @category   Zend
 * @package    Zend_Form
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Bar extends \Zend_File_Transfer_Adapter_Abstract
{
    public $received = false;

    public function send($options = null)
    {
        return;
    }

    public function receive($options = null)
    {
        $this->received = true;
        return;
    }

    public function isSent($file = null)
    {
        return false;
    }

    public function isReceived($file = null)
    {
        return $this->received;
    }

    public function isUploaded($files = null)
    {
        return true;
    }

    public function isFiltered($files = null)
    {
        return true;
    }

    public static function getProgress()
    {
        return;
    }
}

Fix ZF-12173: Zend_Form and Zend_Form_Element prefix paths are not prefix agnostic (namespaces). Patch by Antonio J García Lagar.


<?php

namespace spec\Cerbero\SkeletonTest;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class CiaoSpec extends ObjectBehavior
{
    public function it_is_initializable()
    {
        $this->shouldHaveType('Cerbero\SkeletonTest\Ciao');
    }
}

Create test for the dummy class

Create test for the dummy class


<?php

use Aedart\Scaffold\Contracts\Collections\TemplateProperties;
use Aedart\Scaffold\Templates\TemplateData;
use Aedart\Testing\Laravel\TestCases\unit\GetterSetterTraitTestCase;
use Mockery as m;

/**
 * Class TemplateDataTraitTest
 *
 * @group traits
 * @group templates
 * @group templateData
 *
 * @coversDefaultClass Aedart\Scaffold\Templates\TemplateData
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
class TemplateDataTraitTest extends GetterSetterTraitTestCase
{

    public function _after()
    {
        m::close();
    }

    /**
     * Returns the class path to the trait in question
     *
     * @return string
     */
    public function getTraitClassPath()
    {
        return TemplateData::class;
    }

    /**
     * Returns the name of the property, which the given
     * trait has implemented its getter and setter methods
     *
     * @return string
     */
    public function propertyName()
    {
        return 'templateData';
    }

    /**
     * Returns a Template Properties collection mock
     *
     * @return m\MockInterface|TemplateProperties
     */
    public function makeCollection()
    {
        return m::mock(TemplateProperties::class);
    }

    /***********************************************************
     * Actual tests
     **********************************************************/

    /**
     * @test
     *
     * @covers ::setTemplateData
     * @covers ::getTemplateData
     * @covers ::hasTemplateData
     * @covers ::hasDefaultTemplateData
     * @covers ::getDefaultTemplateData
     */
    public function runTemplateDataTraitMethods(){
        $this->assertGetterSetterTraitMethods($this->makeCollection(), $this->makeCollection());
    }
}

Add Template Properties collection utility test


<?php

class Beeminder_Tests_HttpDriver_CurlTest extends PHPUnit_Framework_TestCase
{
    public function testInstantiation()
    {
        $driver = new Beeminder_HttpDriver_Curl();
        $this->assertTrue( $driver instanceof Beeminder_HttpDriver_Curl );

    }

    public function getCurlMock()
    {
        return $this->getMockBuilder( 'Beeminder_HttpDriver_Curl' )
            ->setMethods(array('_call'))
            ->getMock();
    }

    public function testExecute()
    {
        $driver = $this->getCurlMock();

        $url = 'localhost';
        $parameters = array();
        $method = 'GET';

        $options = array(
            'http_port' => 823,
            'user_agent' => 'testing',
            'timeout' => 5,
            'username' => null,
        );

        $curl_options = array (
                CURLOPT_URL            => 'localhost',
                CURLOPT_USERAGENT      => 'testing',
                CURLOPT_PORT           => 823,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT        => 5,
            );

        $some_fake_json = '{ "hello":"world" }';
        $curl_reply = array(
            'response' => $some_fake_json,
            'headers' => array( 'http_code' => 200 ),
            'error_number' => ''
        );

        $driver->expects( $this->once() )
            ->method( '_call' )
            ->with( $curl_options )
            ->will( $this->returnValue( $curl_reply ) );

        $response = $driver->execute( $url, $parameters, $method, $options );

        $this->assertEquals( $some_fake_json, $response );
    }

    // FIXME: This test doesnt belong with the curl stuff.
    public function testExecute_OAUTH_Token()
    {

    }

    // FIXME: This test doesnt belong with the curl stuff.
    public function testExecute_AUTH_PRIVATE_Token()
    {

    }

    // FIXME: This test doesnt belong with the curl stuff.
    public function testExecute_QueryParameters()
    {

    }

}

Add initial tests for Beeminder_HttpDriver_Curl


<?php

require_once __DIR__ . "/tester_autoload.php";

class RpcQueueTest extends \PHPUnit_Framework_TestCase {

	function test_rpc_call_timeout() {
		$log = new \Psr\Log\NullLogger();
		$q = \GMO\Beanstalk\RpcQueue::getInstance($log, HOST, PORT);

		try {
			$q->runRpc('queueWithNoWorkers', array(), 1);
		} catch(\GMO\Beanstalk\Exception\RpcTimeoutException $e) {
			$this->assertEquals('Timed Out', $e->getMessage());
			return;
		}

		$this->fail('Exception \GMO\Beanstalk\Exception\RpcTimeoutException was not thrown.');
	}

	static function tearDownAfterClass() {
		$log = new \Psr\Log\NullLogger();
		$q = \GMO\Beanstalk\Queue::getInstance($log, HOST, PORT);

		foreach ($q->listTubes() as $tube) {
			$q->deleteReadyJobs($tube);
			$q->deleteDelayedJobs($tube);
			$q->deleteBuriedJobs($tube);
		}
	}
}

Add unit test for RpcQueue

Add unit test for RpcQueue


<?php
namespace Koala\ContentBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Koala\ContentBundle\Entity\Page;
use Koala\ContentBundle\Entity\Region;

class SetupCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('koala_content:setup')
            ->setDescription('Setup default content for KoalaContentBundle')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $doctrine = $this->getContainer()->get('doctrine');
        $em = $doctrine->getEntityManager();
        $repository = $em->getRepository('KoalaContentBundle:Page');

        /* Add a default Main Menu and a Welcome page */
        $menu = new Page();
        $menu->setMenuTitle('Main Menu');
        $menu->setSlug('main_menu');
        $menu->setLayout('');
        $repository->persistAsFirstChild($menu);

        $page = new Page();
        $page->setMenuTitle('Welcome');
        $page->setSlug('welcome');
        $page->setUrl('/');
        $page->setLayout('default');
        $repository->persistAsFirstChildOf($page, $menu);

        $region = new Region();
        $region->setPage($page);
        $region->setName('content');
        $region->setContent(<<<EOT

Hello World

This is KoalaContentBundle - the simple CMS based on Mercury Editor. Just click this content to be able to edit it.

See KoalaContentBundle for more information.

EOT
        );
        $em->persist($region);

        $em->flush();
    }
}

Add a koala_content:setup command which creates some default content


<?php
/**
 * This file is part of the bee4/transport package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2015
 * @author  Stephane HULARD <s.hulard@chstudio.fr>
 * @package Bee4\Transport
 */

namespace Bee4\Transport;

use Bee4\Transport\Message\Request\AbstractRequest;

/**
 * Add some magic method handling to the default client
 * @package Bee4\Transport
 *
 * @method AbstractRequest get(string $url = "", array $headers = [])
 * @method AbstractRequest post(string $url = "", array $headers = [])
 * @method AbstractRequest head(string $url = "", array $headers = [])
 * @method AbstractRequest delete(string $url = "", array $headers = [])
 * @method AbstractRequest put(string $url = "", array $headers = [])
 */
class MagicHandler implements ClientInterface
{
	protected $client;

	/**
	 * @param Client $c
	 */
	public function __construct( Client $c ) {
		$this->client = $c;
	}

	/**
	 * Send decoration, rely to given client
	 * @param  AbstractRequest $request
	 * @return Message\Response
	 */
	public function send( AbstractRequest $request ) {
		return $this->client->send($request);
	}

	/**
	 * Create decoration, rely to given client
	 * @param string $method
	 * @param string $url
	 * @param array $headers
	 * @return AbstractRequest
	 */
	public function createRequest( $method, $url = '', array $headers = [] ) {
		return $this->client->createRequest($method, $url, $headers);
	}

	/**
	 * Magic method to implement dynamically all request types that are defined.
	 * The request factory can't build a valid object, an exception is thrown
	 * @param string $name The method name
	 * @param array $arguments Argument collection to be used to build request
	 * @return AbstractRequest
	 */
	public function __call( $name, array $arguments = [] ) {
		//Send all others method directly to the client
		if( method_exists($this->client, $name) ) {
			return call_user_func_array([$this->client, $name], $arguments);
		}

		//Then handle magic HTTP name calls
		$arguments[0] = isset($arguments[0])?$arguments[0]:'';
		array_unshift($arguments, $name);
		return call_user_func_array([$this, 'createRequest'], $arguments);
	}
}

Add a Client decorator to handle __call behaviour

Signed-off-by: Stéphane HULARD <a24f38cb8c57ec2778c80a9f0c151933508927e5@chstudio.fr>


<?php

require_once 'webservice/db.php';

/**
 * Abstract Base class for all web services.
 */
abstract class WebService {

    /**
     * Executes the web service.
     * @param Array $data User-specified parameters. Usually, url parameters are included as $data[query1], $data[query2],... and $_GET and _POST are merged in
     */
    abstract public function execute($data);

    /**
     * ouputs $dataArray as (on php>=5.4 pretty) JSON
     * @param Array $dataArray
     */
    public static function output($dataArray) {
        echo json_encode($dataArray, defined('JSON_PRETTY_PRINT')?JSON_PRETTY_PRINT:0);
    }

    /**
     * factory method for all web services
     * creates an instance of the class called by querystring. additional parameters are returned in $parameters as query1, query2, etc.
     * e.g.
     * <code>
     * WebService::factory('details/organism/12345');
     * // =>
     * return array(new \ajax\details\Organism(), array('query1'=>'12345'));
     * </code>
     * @param String $servicePath
     * @return list($instance, $parameters)
     */
    public static function factory($servicePath) {
        $serviceBasePath = __DIR__ . DIRECTORY_SEPARATOR . 'ajax';

        //search in ./$path[0]/.../($path[x])/ for ucfirst($path[x+1]).php.
        $path = explode('/', $servicePath);
        $filepath = $serviceBasePath . DIRECTORY_SEPARATOR . $path[0];
        $serviceNamespace = '\\ajax\\' . $path[0];
        $args = array();
        for ($i = 1; $i < count($path); $i++) {
            $classname = ucfirst($path[$i]);
            $filename = $filepath . DIRECTORY_SEPARATOR . $classname . '.php';
            if (file_exists($filename)) {
                for ($j = $i + 1; $j < count($path); $j++) {
                    $args['query' . ($j - $i)] = $path[$j];
                }
                break;
            }
            $filepath .= DIRECTORY_SEPARATOR . strtolower($path[$i]);
            $serviceNamespace .= '\\' . strtolower($path[$i]);
        }

        //case: no service file found
        if (!isset($filename) || !file_exists($filename)) {
            return array(null, null);
        }
        //case: service path tries to escape from basePath
        if (!(strpos(realpath($filename), realpath($serviceBasePath)) === 0)) {
            return array(null, null);
        }
        require_once $filename;
        //case: file does not contain web service class
        $class = $serviceNamespace . '\\' . $classname;
        if (!class_exists($class)) {
            return array(null, null);
        }

        return array(new $class, $args);
    }

}

?>

Add generic webservice class (factory to create webservices from path)


<?php
/**
 * Makes sure there are spaces between the concatenation operator (.) and
 * the strings being concatenated.
 * @name Snap_Sniffs_Strings_ConcatenationSpacingSniff
 */
class Snap_Sniffs_Strings_ConcatenationSpacingSniff implements PHP_CodeSniffer_Sniff {

	/**
	 * Returns an array of tokens this test wants to listen for.
	 * @return array
	 */
	public function register() {
		return array(T_STRING_CONCAT);
	}

	/**
	 * Run whenever a '.' is encountered
	 *
	 * @param PHP_CodeSniffer_File $file The file being scanned.
	 * @param int $stack_ix The position of the current token in the stack
	 */
	public function process(PHP_CodeSniffer_File $file, $stack_ix) {
		$tokens = $file->getTokens();
		if (
			$tokens[($stack_ix - 1)]['code'] !== T_WHITESPACE
			|| $tokens[($stack_ix + 1)]['code'] !== T_WHITESPACE
		) {
			$file->addError('Concat operator must be surrounded by spaces', $stack_ix, 'ConcatUnspaced');
		}
	}
}

Enforce spaces around concat operator

Enforce spaces around concat operator


<?php
/**
 * This will change the notify_url sent to PayPal during PayPal Standard payments.
 *
 * By default, RCP sends the local site URL. If you're developing on localhost
 * or some other domain that isn't accessible to PayPal, and you're using
 * a tunnel like ngrok, this will help you get the PayPal IPN data.
 */
add_filter( 'rcp_paypal_args', function( $args ) {
	$args['notify_url'] = 'https://x.ngrok.io/index.php?listener=IPN'; // replace x.grok.io with the desired URL
	return $args;
});

Add PayPal notify_url override example.

Add PayPal notify_url override example.


<?php

namespace Mimic\Test;

use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;

/**
 * Unit Test for dropFirst Mimic library function.
 *
 * @since 0.1.0
 */
class InvokeFirstFuncTest extends PHPUnit_Framework_TestCase {
	/**
	 * @covers ::Mimic\Functional\invokeFirst
	 */
	public function testDummy_Invoke_exists() {
		$collection = array(new Dummy\Invoke, new Dummy\Invoke);
		$expected = true;
		$actual = F\invokeFirst($collection, 'exists');
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\invokeFirst
	 */
	public function testDummy_Invoke_with() {
		$collection = array(new Dummy\Invoke, new Dummy\Invoke);
		$expected = array(1, 2, 3);
		$actual = F\invokeFirst($collection, 'with', $expected);
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\invokeFirst
	 */
	public function testMethodDoesNotExist() {
		$collection = array(new Dummy\Invoke, new Dummy\Invoke);
		$expected = null;
		$actual = F\invokeFirst($collection, '__doesnotexist__');
		$this->assertEquals($expected, $actual);
	}

	/**
	 * @covers ::Mimic\Functional\invokeFirst
	 */
	public function testClassMethod() {
		$collection = array('\Mimic\Test\Dummy\Invoke', '\Mimic\Test\Dummy\Invoke');
		$expected = true;
		$actual = F\invokeFirst($collection, 'method');
		$this->assertEquals($expected, $actual);
	}
}

Add invoke first function test suite.

Add invoke first function test suite.


<?php
namespace Sil\SilAuth\mfa;

class MfaInfo
{
    const EMPLOYEE_ID = 'employee_id';
    const MFA_OPTIONS = 'mfa_options';
    const PROMPT_FOR_MFA = 'prompt_for_mfa';

    /**
     * The Employee ID that this MFA info is for.
     *
     * @var string
     */
    private $employeeId;

    /**
     * A list of MFA options available to the user.
     *
     * @var array
     */
    private $mfaOptions;

    /**
     * Whether to prompt the user for MFA ("yes" or "no").
     *
     * @var string
     */
    private $promptForMfa;

    public function __construct(
        string $employeeId,
        string $promptForMfa,
        array $mfaOptions
    ) {
        $this->employeeId = $employeeId;
        $this->promptForMfa = $promptForMfa;
        $this->mfaOptions = $mfaOptions;
    }

    /**
     * Create an MfaInfo object from the values in the given array.
     *
     * @param array $info
     * @return MfaInfo
     */
    public static function createFromArray($info)
    {
        return new MfaInfo(
            $info[self::EMPLOYEE_ID],
            $info[self::PROMPT_FOR_MFA],
            $info[self::MFA_OPTIONS] ?? []
        );
    }

    public function getEmployeeId()
    {
        return $this->employeeId;
    }

    protected static function isNo($text)
    {
        return (strtolower($text) === 'no');
    }

    public function shouldPromptForMfa()
    {
        return !self::isNo($this->promptForMfa);
    }
}

Add helper class for handling MFA information.


<?php

declare(strict_types=1);

namespace Ordermind\LogicalPermissions\PermissionTree;

class PermissionTreeNodeValue
{
    private bool $internalValue;

    /**
     * @param array|string|bool $permissions
     */
    private $permissions;

    /**
     * @var self[]
     */
    private array $childValues;

    /**
     * @param array|string|bool $permissions
     */
    public function __construct(bool $internalValue, $permissions, self ...$childValues)
    {
        $this->internalValue = $internalValue;
        $this->permissions = $permissions;
        $this->childValues = $childValues;
    }

    public function getInternalValue(): bool
    {
        return $this->internalValue;
    }

    /**
     * @return array|string|bool $permissions
     */
    public function getPermissions()
    {
        return $this->permissions;
    }

    public function getChildValues(): array
    {
        return $this->childValues;
    }
}

Add class for holding tree node value including debug info


<?php

use Phinx\Migration\AbstractMigration;

class AddImageTimes extends AbstractMigration
{
    public function change()
    {
      $table= $this->table('image', [ 'signed' => false ]);
      $table
        /* Don't use ->addTimestamps() because we use DATETIME */
        ->addColumn('created_at', 'datetime', [
                      'default' => 'CURRENT_TIMESTAMP',
                    ])
        ->addColumn('updated_at', 'datetime', [
                      'update' => 'CURRENT_TIMESTAMP',
                      'default' => 'CURRENT_TIMESTAMP',
                    ])
        ->addIndex(['created_at'])
        ->save();
    }
}

Add created/updated times to image table


Order History

            Generate Sales Order Report

                    Ordered by
                    Date
                    Time
                    Product Name
                    Quantity
                    Price

            <?php foreach ($query as $row): { ?>

                <?php echo $row['username'];?>
                <?php echo $row['date'];?>
                <?php echo $row['time'];?>
                <?php echo $row['pname'];?>
                <?php echo $row['quantity'];?>
                <?php echo $row['price'];?>

            <?php } ?>
            <?php endforeach; ?>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Confirm Purchase

              <form method = "post" action="addinventory" name="addinventory">

What inventory item would you like to add?

                  <input type="text" placeholder="Item Name" class="form-control" id="invname" name="invname">
                  <input type="number" placeholder="Item Quantity" class="form-control" id="invqty" name="invqty">
                  <input type="number" placeholder="Item Classification" class="form-control" id="invclass" name="invclass">

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                <input type="submit" class = "btn btn-primary" value="Confirm">
                </form>

Create new page for admin order history.


<?php

require BASEPATH . 'helpers/path_helper.php';

class Path_helper_test extends CI_TestCase
{
	public function test_set_realpath()
	{
		$expected = getcwd() . '/';
		$this->assertEquals($expected, set_realpath(getcwd()));
	}

	public function test_set_realpath_nonexistent_directory()
	{
		$expected = '/path/to/nowhere';
		$this->assertEquals($expected, set_realpath('/path/to/nowhere', FALSE));
	}

	public function test_set_realpath_error_trigger()
	{
		$this->setExpectedException(
				'RuntimeException', 'CI Error: Not a valid path: /path/to/nowhere'
		);

		set_realpath('/path/to/nowhere', TRUE);
	}
}

/* End of file path_helper_test.php */

<?php

require BASEPATH . 'helpers/path_helper.php';

class Path_helper_test extends CI_TestCase
{
	public function test_set_realpath()
	{
		$expected = getcwd() . DIRECTORY_SEPARATOR;
		$this->assertEquals($expected, set_realpath(getcwd()));
	}

	public function test_set_realpath_nonexistent_directory()
	{
		$expected = '/path/to/nowhere';
		$this->assertEquals($expected, set_realpath('/path/to/nowhere', FALSE));
	}

	public function test_set_realpath_error_trigger()
	{
		$this->setExpectedException(
				'RuntimeException', 'CI Error: Not a valid path: /path/to/nowhere'
		);

		set_realpath('/path/to/nowhere', TRUE);
	}
}

/* End of file path_helper_test.php */

Add fix for Windows OS

Add fix for Windows OS


<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Mail\GeneralInterestInvite as Mailable;
use Illuminate\Notifications\Messages\MailMessage;

class GeneralInterestNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @param \App\FasetVisit $visit
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return Mailable
     */
    public function toMail($notifiable)
    {
        return (new Mailable($notifiable->visit_token))->to($notifiable->faset_email);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Create Notification for sending GI mailable


#!/usr/bin/php
<?php

// HTTPFUL Library
// http://phphttpclient.com/
include "../../httpful/httpful.phar";

// Use PHP Library from
// http://csv.thephpleague.com/
use League\Csv\Writer;
require '../../league_csv/vendor/autoload.php';

include "../MonsumAPI.php";
include "../MonsumProduct.php";
include "../MonsumProducts.php";

date_default_timezone_set("Europe/Zurich");

$a = new MonsumAPI(array(MonsumAPI::MONSUM_API_CACHE     => true,
                         MonsumAPI::MONSUM_API_CACHE_DIR => "./cache", // no trailing slash
                         MonsumAPI::MONSUM_API_CACHE_AGE => 300, // 5 minutes
                         MonsumAPI::MONSUM_API_DEBUG     => false,
                         MonsumAPI::MONSUM_API_LOGFILE   => "./log/monsum_api.log",
                         MonsumAPI::MONSUM_API_URL       => "https://app.monsum.com/api/1.0/api.php",
                         MonsumAPI::MONSUM_API_KEY       => "123",
                         MonsumAPI::MONSUM_API_EMAIL     => "user@domain.tld"));

$writer = Writer::createFromPath("monsum_products.csv", "w");
$writer->insertOne(["id", "number", "title", "description", "isgross", "unitprice", "setupfee", "allowmultiple",
                    "currencycode", "isdigital", "vatpercent", "sinterval", "snumevents", "strial", "sduration",
                    "sdurationfollow", "sdurationcancel", "isaddon"]);

$p = new MonsumProducts($a);
foreach ($p as $key => $value) {
    $writer->insertOne([$value->getID(),
                        $value->getNumber(),
                        $value->getTitle(),
                        $value->getDescription(),
                        $value->isGross(),
                        $value->getUnitPrice(),
                        $value->getSetupFee(),
                        $value->allowMultiple(),
                        $value->getCurrencyCode(),
                        $value->isDigital(),
                        $value->getVATPercent(),
                        $value->getSubscriptionInterval(),
                        $value->getSubscriptionNumberEvents(),
                        $value->getSubscriptionTrial(),
                        $value->getSubscriptionDuration(),
                        $value->getSubscriptionDurationFollow(),
                        $value->getSubscriptionCancellation(),
                        $value->isAddon()
                        ]);
}

?>

Add example for CSV export

Add example for CSV export


<?php
namespace Listabierta\Bundle\MunicipalesBundle\Form\Model;

use Symfony\Component\Security\Core\Validator\Constraints as SecurityAssert;
use Symfony\Component\Validator\Constraints as Assert;

class ChangePassword
{
    /**
     * @SecurityAssert\UserPassword(
     *     message = "Wrong value for your current password"
     * )
     */
     protected $oldPassword;

    /**
     * @Assert\Length(
     *     min = 6,
     *     minMessage = "Password should by at least 6 chars long"
     * )
     */
     protected $newPassword;
}

Add model form type for change password

Add model form type for change password


<?php namespace Aedart\Scaffold\Exceptions;

use RuntimeException;

/**
 * Cannot Process Template Exception
 *
 * Throw this exception whenever a template cannot be processed, e.g. when
 * it cannot build a file, based on the given template or perhaps it is
 * missing some configuration, etc.
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Exceptions
 */
class CannotProcessTemplateException extends RuntimeException
{

}

Fix missing cannot process template exception


<?php

namespace Tests\AppBundle\API\Listing;

use AppBundle\AppBundle;
use AppBundle\DB;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

class TaxonomyTest extends WebTestCase
{

    public function testExecute()
    {
        $client = static::createClient();
        $default_db = $client->getContainer()->getParameter('default_db');
        $session = null;
        $organisms = $client->getContainer()->get('app.api.webservice')->factory('listing', 'taxonomy');
        $parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => '1234'));
        $results = $organisms->execute($parameterBag, $session);
        $expected = array(
            "lineage" => array(
                "Viridiplantae",
                "Streptophyta",
                "Streptophytina",
                "Embryophyta",
                "Tracheophyta",
                "Euphyllophyta",
                "Spermatophyta",
                "Magnoliophyta",
                "Mesangiospermae",
                "eudicotyledons",
                "Gunneridae",
                "Pentapetalae",
                "rosids",
                "malvids",
                "Sapindales",
                "Aceraceae",
                "Acer",
                "Acer macrophyllum"
            )
        );
        $this->assertEquals($expected, $results);
    }
}

Add test for listing taxonomy webservice


<?php
namespace Spika\Provider;

use Spika\Db\CouchDb;
use Spika\Db\MySQL;
use Silex\Application;
use Silex\ServiceProviderInterface;

class SpikaDbServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
       /* $app['spikadb'] = $app->share(function () use ($app) {
            return new CouchDb(
                $app['couchdb.couchDBURL'],
                $app['logger']
            );
        });
       */

        $app['spikadb'] = $app->share(function () use ($app) {
            return new MySQL(
                $app['couchdb.couchDBURL'],
                $app['logger'],
                $app['db']
            );
        });

    }

    public function boot(Application $app)
    {
    }
}

<?php
namespace Spika\Provider;

use Spika\Db\CouchDb;
use Spika\Db\MySql;
use Silex\Application;
use Silex\ServiceProviderInterface;

class SpikaDbServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
       /* $app['spikadb'] = $app->share(function () use ($app) {
            return new CouchDb(
                $app['couchdb.couchDBURL'],
                $app['logger']
            );
        });
       */

        $app['spikadb'] = $app->share(function () use ($app) {
            return new MySQL(
                $app['couchdb.couchDBURL'],
                $app['logger'],
                $app['db']
            );
        });

    }

    public function boot(Application $app)
    {
    }
}

Fix to load MySql Class

Fix to load MySql Class


<?php
/**
 * @author Jean Silva <me@jeancsil>
 * @license MIT
 */
namespace Jeancsil\FlightSpy\Log;

use Monolog\Logger;
use Psr\Log\LoggerAwareTrait;

class ArrayLogger extends Logger
{
    use LoggerAwareTrait;

    const COLOR_NONE = "[0m";
    const COLOR_RED = "[31m";
    const COLOR_GREEN = "[32m";
    const COLOR_YELLOW = "[33m";

    public function debug($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::debug($this->format($item), $context);
        }
    }

    public function info($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::info($this->format($item), $context);
        }
    }

    public function notice($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::notice($this->format($item), $context);
        }
    }

    public function warn($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::warn($this->format($item), $context);
        }
    }

    public function error($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::error($this->format($item, self::COLOR_RED), $context);
        }
    }

    public function critical($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::critical($this->format($item, self::COLOR_YELLOW), $context);
        }
    }

    public function alert($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::alert($this->format($item), $context);
        }
    }

    public function emergency($items, array $context = [])
    {
        foreach ((array) $items as $item) {
            parent::emergency($this->format($item), $context);
        }
    }

    private function format($message, $color = self::COLOR_GREEN)
    {
        return chr(27) . "$color$message" . chr(27). self::COLOR_NONE;
    }
}

Allow arrays to be logged in a more readable way


<?php

/*
 * Copyright (C) 2013 Kolibre
 *
 * This file is part of Kolibre-KADOS.
 * Kolibre-KADOS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or
 * at your option) any later version.
 *
 * Kolibre-KADOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Kolibre-KADOS. If not, see <http://www.gnu.org/licenses/>.
 */

$includePath = dirname(realpath(__FILE__)) . '/../../../include/types';
set_include_path(get_include_path() . PATH_SEPARATOR . $includePath);

require_once('getServiceAttributesResponse.class.php');

class getServiceAttributesResponseTest extends PHPUnit_Framework_TestCase
{
    protected $serviceAttributes;

    public function setUp()
    {
        $serviceProvider = null;
        $service = null;
        $supportedContentSelectionMethods = new supportedContentSelectionMethods(array('OUT_OF_BAND'));
        $supportsServerSideBack = false;
        $supportsSearch = false;
        $supportedUplinkAudioCodecs = new supportedUplinkAudioCodecs();
        $supportsAudioLabels = false;
        $supportedOptionalOperations = new supportedOptionalOperations();
        $this->serviceAttributes = new serviceAttributes(
            $serviceProvider,
            $service,
            $supportedContentSelectionMethods,
            $supportsServerSideBack,
            $supportsSearch,
            $supportedUplinkAudioCodecs,
            $supportsAudioLabels,
            $supportedOptionalOperations);
    }

    /**
     * @group getServiceAttributesResponse
     * @group validate
     */
    public function testServiceAttributes()
    {
        $instance = new getServiceAttributesResponse();
        $this->assertFalse($instance->validate());
        $this->assertContains('getServiceAttributesResponse.serviceAttributes', $instance->getError());
        $instance->serviceAttributes = $this->serviceAttributes;
        $this->assertTrue($instance->validate());
    }
}

?>

Add unit tests for getServiceAttributesResponse class


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Quick access to web logs</title>

<?php

$commands = [
	"sudo tail -n50 /var/log/apache2/error.log",
	"sudo tail -n50 /var/log/apache2/other_vhosts_access.log"
];

foreach($commands as $command)
{
	$htmlcommand = htmlspecialchars($command);
	echo "
$htmlcommand
\n";

	$results = null;
	exec($command, $results);
	echo("
\n".implode("\n",$results)."\n
\n");
}

?>

Add simple website to get apache error logs


<?php
namespace App\Test\TestCase\Model\Entity;

use App\Model\CurrentUser;
use App\Model\Entity\Sentence;
use App\Model\Entity\Transcription;
use Cake\TestSuite\TestCase;

class TranscriptionTest extends TestCase
{
    public $fixtures = array(
            'app.users_languages'
    );

    public function setUp()
    {
        parent::setUp();
        CurrentUser::store([
            'id' => 1,
            'role' => \App\Model\Entity\User::ROLE_CORPUS_MAINTAINER,
        ]);
    }

    function makeTranscription($lang, $sourceScript, $targetScript, $text) {
        $transcription = new Transcription();
        $transcription->sentence = new Sentence();
        $transcription->sentence->lang = $lang;
        $transcription->sentence->script = $sourceScript;
        $transcription->script = $targetScript;
        $transcription->text = $text;

        return $transcription;
    }

    public function testGetHtml_jpn()
    {
        $this->assertEquals(
            '「<ruby>何<rp>（</rp><rt>なに</rt><rp>）</rp></ruby>？」',
            $this->makeTranscription('jpn', 'Jpan', 'Hrkt', '「[何|なに]？」')->html
        );

        $this->assertEquals(
            '<!--',
            $this->makeTranscription('jpn', 'Jpan', 'Hrkt', '<!--')->html
        );
    }

    public function testGetHtml_cmn()
    {
        $this->assertEquals(
            '"Shénme?"',
            $this->makeTranscription('cmn', 'Hans', 'Latn', '"Shen2me5?"')->html
        );
    }

    public function testGetHtml_uzb()
    {
        $this->assertEquals(
            '"Nima?"',
            $this->makeTranscription('uzb', 'Cyrl', 'Latn', '"Nima?"')->html
        );
    }

    public function testGetMarkup_jpn()
    {
        $this->assertEquals(
            '「何｛なに｝？」',
            $this->makeTranscription('jpn', 'Jpan', 'Hrkt', '「[何|なに]？」')->markup
        );

        $this->assertEquals(
            '<!--',
            $this->makeTranscription('jpn', 'Jpan', 'Hrkt', '<!--')->markup
        );
    }

    public function testGetMarkup_cmn()
    {
        $this->assertEquals(
            '"Shen2me5?"',
            $this->makeTranscription('cmn', 'Hant', 'Latn', '"Shen2me5?"')->markup
        );
    }

    public function testGetMarkup_uzb()
    {
        $this->assertEquals(
            '',
            $this->makeTranscription('uzb', 'Latn', 'Cyrl', '"Nima?"')->markup
        );
    }
}

Add tests for turning transcriptions into HTML and markup


<?php

namespace spec\SyliusLabs\RabbitMqSimpleBusBundle\Denormalizer;

use PhpAmqpLib\Message\AMQPMessage;
use PhpSpec\ObjectBehavior;
use SyliusLabs\RabbitMqSimpleBusBundle\Denormalizer\DenormalizationFailedException;
use SyliusLabs\RabbitMqSimpleBusBundle\Denormalizer\DenormalizerInterface;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
final class CompositeDenormalizerSpec extends ObjectBehavior
{
    function it_is_a_denormalizer()
    {
        $this->shouldImplement(DenormalizerInterface::class);
    }

    function it_does_not_support_a_message_if_there_are_no_denormalizers()
    {
        $amqpMessage = new AMQPMessage('Message body');

        $this->supports($amqpMessage)->shouldReturn(false);
        $this->shouldThrow(DenormalizationFailedException::class)->during('denormalize', [$amqpMessage]);
    }

    function it_supports_a_message_if_at_least_one_of_denormalizers_support_it(
        DenormalizerInterface $firstDenormalizer,
        DenormalizerInterface $secondDenormalizer
    ) {
        $amqpMessage = new AMQPMessage('Message body');
        $denormalizedMessage = new \stdClass();

        $firstDenormalizer->supports($amqpMessage)->willReturn(false);
        $firstDenormalizer->denormalize($amqpMessage)->shouldNotBeCalled();
        $secondDenormalizer->supports($amqpMessage)->willReturn(true);
        $secondDenormalizer->denormalize($amqpMessage)->willReturn($denormalizedMessage);

        $this->addDenormalizer($firstDenormalizer);
        $this->addDenormalizer($secondDenormalizer);

        $this->supports($amqpMessage)->shouldReturn(true);
        $this->denormalize($amqpMessage)->shouldReturn($denormalizedMessage);
    }

    function it_does_not_support_a_message_if_none_of_the_denormalizers_support_it(
        DenormalizerInterface $firstDenormalizer,
        DenormalizerInterface $secondDenormalizer
    ) {
        $amqpMessage = new AMQPMessage('Message body');

        $firstDenormalizer->supports($amqpMessage)->willReturn(false);
        $firstDenormalizer->denormalize($amqpMessage)->shouldNotBeCalled();
        $secondDenormalizer->supports($amqpMessage)->willReturn(false);
        $secondDenormalizer->denormalize($amqpMessage)->shouldNotBeCalled();;

        $this->addDenormalizer($firstDenormalizer);
        $this->addDenormalizer($secondDenormalizer);

        $this->supports($amqpMessage)->shouldReturn(false);
        $this->shouldThrow(DenormalizationFailedException::class)->during('denormalize', [$amqpMessage]);
    }
}

Add tests for composite denormalizer

Add tests for composite denormalizer


<?php

class CM_Response_Resource_Css_VendorTest extends CMTest_TestCase {

    public function testProcess() {
        $render = new CM_Frontend_Render(new CM_Frontend_Environment());
        $request = new CM_Request_Get($render->getUrlResource('vendor-css', 'all.css'));
        $response = new CM_Response_Resource_Css_Vendor($request);
        $response->process();
        $this->assertContains('body{', $response->getContent());
    }
}

Add test for css vendor response

Add test for css vendor response


<?php

namespace Omnipay\UnionPay\Common;

/**
 * String Util for UnionPay
 * Class StringUtil
 * @package Omnipay\UnionPay\Common
 */
class StringUtil
{
    public static function parseFuckStr($str, $data = array())
    {
        preg_match_all('#(?<k>[^=]+)=(?<v>[^&{]+|{[^}]+}|\[[^]]+])&?#', $str, $matches);

        foreach ($matches['k'] as $i => $key) {
            $data[$key] = $matches['v'][$i];
        }

        return $data;
    }
}

Add a special QueryString parser....

Add a special QueryString parser....


<?php namespace Tev\Bs\Endpoint\Bookings;

use Buzz\Message\RequestInterface;
use Tev\Bs\Endpoint\AbstractEndpoint;

/**
 * Endpoint object for /api/bookings/:id.
 *
 * See: /docs/endpoints#bookings-update
 */
class UpdateEndpoint extends AbstractEndpoint {

    /**
     * ID of Booking to udpate.
     *
     * @var string
     */
    private $bookingId;

    /**
     * Constructor.
     *
     * Set Booking ID.
     *
     * @param  string $bookingId ID of Booking to update
     * @return void
     */
    public function __construct($bookingId)
    {
        parent::__construct();

        $this->method = RequestInterface::METHOD_PUT;

        $this->bookingId = $bookingId;
    }

    /**
     * Retrieve the API URL for this endpoint.
     *
     * @return string
     */
    protected function apiUrl()
    {
        return "/api/bookings/{$this->bookingId}";
    }
}

Add new Bookings - Update endpoint

Add new Bookings - Update endpoint


<?php

declare(strict_types=1);
/**
 * @copyright Copyright (c) 2021 Joas Schilling <coding@schilljs.com>
 *
 * @author Joas Schilling <coding@schilljs.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

namespace OC\Core\Migrations;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version21000Date20210309185127 extends SimpleMigrationStep {
	/**
	 * @param IOutput $output
	 * @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
	 * @param array $options
	 * @return null|ISchemaWrapper
	 */
	public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
		/** @var ISchemaWrapper $schema */
		$schema = $schemaClosure();

		$table = $schema->getTable('known_users');
		if (!$table->hasIndex('ku_known_user')) {
			$table->addIndex(['known_user'], 'ku_known_user');
			return $schema;
		}

		return null;
	}
}

Add missing index on the user column

Add missing index on the user column

Signed-off-by: Joas Schilling <ab43a7c9cb5b2380afc4ddf8b3e2583169b39a02@schilljs.com>


<?php

namespace Kevinrob\GuzzleCache\Storage;

use Doctrine\Common\Cache\Cache;
use Kevinrob\GuzzleCache\CacheEntry;

class CompressedDoctrineCacheStorage implements CacheStorageInterface
{
    /**
     * @var Cache
     */
    protected $cache;

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

    /**
     * {@inheritdoc}
     */
    public function fetch($key)
    {
        try {
            $cache = unserialize(gzuncompress($this->cache->fetch($key)));
            if ($cache instanceof CacheEntry) {
                return $cache;
            }
        } catch (\Exception $ignored) {
            return;
        }

        return;
    }

    /**
     * {@inheritdoc}
     */
    public function save($key, CacheEntry $data)
    {
        try {
            $lifeTime = $data->getTTL();
            if ($lifeTime >= 0) {
                return $this->cache->save(
                    $key,
                    gzcompress(serialize($data)),
                    $lifeTime
                );
            }
        } catch (\Exception $ignored) {
            // No fail if we can't save it the storage
        }

        return false;
    }
}

Add compressed doctrine storage stratrgy


<?php
namespace TYPO3\Flow\Tests\Unit\Utility;

/*                                                                        *
 * This script belongs to the TYPO3 Flow framework.                       *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 * of the License, or (at your option) any later version.                 *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

use TYPO3\Flow\Utility\Algorithms;

/**
 * Testcase for the Utility Algorithms class
 *
 */
class AlgorithmsTest extends \TYPO3\Flow\Tests\UnitTestCase {

	/**
	 * @test
	 */
	public function generateUUIDGeneratesUuidLikeString() {
		$this->assertRegExp('/^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/', Algorithms::generateUUID());
	}

	/**
	 * @test
	 */
	public function generateRandomBytesGeneratesRandomBytes() {
		$this->assertEquals(20, strlen(Algorithms::generateRandomBytes(20)));
	}

	/**
	 * @test
	 */
	public function generateRandomTokenGeneratesRandomToken() {
		$this->assertRegExp('/^[[:xdigit:]]{64}$/', Algorithms::generateRandomToken(32));
	}

	/**
	 * @test
	 */
	public function generateRandomStringGeneratesAlnumCharactersPerDefault() {
		$this->assertRegExp('/^[a-z0-9]{64}$/i', Algorithms::generateRandomString(64));
	}

	/**
	 * signature: $regularExpression, $charactersClass
	 */
	public function randomStringCharactersDataProvider() {
		return array(
			array('/^[#~+]{64}$/', '#~+'),
			array('/^[a-f2-4%]{64}$/', 'abcdef234%'),
		);
	}

	/**
	 * @test
	 * @dataProvider randomStringCharactersDataProvider
	 */
	public function generateRandomStringGeneratesOnlyDefinedCharactersRange($regularExpression, $charactersClass) {
		$this->assertRegExp($regularExpression, Algorithms::generateRandomString(64, $charactersClass));
	}
}
?>

Add Unit Tests for Utility\Algorithms

[TASK] Add Unit Tests for Utility\Algorithms

This adds Unit Tests for the Utility\Algorithms class and its functions.

Change-Id: I040f2177c4955f05392b9fc0ef6508a90c8fd681
Releases: master, 2.0
Original-Commit-Hash: 936ffe938c27361bab71f34c3e7bafbbc2319dad


<?php
/*
 * This file is part of the Artscore Studio Framework package.
 *
 * (c) Nicolas Claverie <info@artscore-studio.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ASF\LayoutBundle\Tests\Twig\Extension;

use ASF\LayoutBundle\Twig\Extension\SupportsExtension;

/**
 * Supoprted assets Twig Extension
 *
 * @author Nicolas Claverie <info@artscore-studio.fr>
 *
 */
class SupportsTwigExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \ASF\LayoutBundle\Twig\Extension\SupportsExtension
     */
    protected $twigExtension;

    /**
     * {@inheritDoc}
     * @see PHPUnit_Framework_TestCase::setUp()
     */
    public function setUp()
    {
        $this->twigExtension = new SupportsExtension();
    }

    /**
     * Assert that SupportsExtension have two function declared
     */
    public function testGetFunctions()
    {
        $this->assertCount(2, $this->twigExtension->getFunctions());
    }

    /**
     * Test getJavascript function with invalid jquery path
     */
    public function testGetJavascriptsWithInvalidJqueryPath()
    {
        $this->setExpectedException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
        $supported_assets = array(
            'jquery' => array(
                'path' => '/path/jquery.min.js'
            )
        );
        $enable_assetic_support = true;

        $this->twigExtension->setSupportedAssets($supported_assets, $enable_assetic_support);
        $this->twigExtension->getJavascripts();
    }
}

Add test for Twig SupportExtension (check if Exception raised when jquery path is invalid)


<?php
/*
 * SolusVM_ConfigOptions
 *
 * Define the settings that are configurable on a per product basis when a product uses the module
 *
 * @package		SolusVM
 * @category	WHMCS Provisioning Modules
 * @author		Trajche Petrov
 * @link		https://qbit.solutions/
*/
	class SolusVM_ConfigOptions extends SolusVM
	{

		function _exec()
		{
			$options = array
			(
				"master" => array
				(
					"FriendlyName" => "Master Server",
					"Type" => "dropdown",
					'Options' => array
					(
					)
				),
				"group" => array
				(
					"FriendlyName" => "Node Group",
					"Type" => "dropdown",
					'Options' => array
					(
					)
				),
				"node" => array
				(
					"FriendlyName" => "Default Node",
					"Type" => "dropdown",
					'Options' => array
					(
					)
				),

				"plan" => array
				(
					"FriendlyName" => "Default Plan",
					"Type" => "dropdown",
					'Options' => array
					(
					)
				),

				"os" => array
				(
					"FriendlyName" => "Default OS",
					"Type" => "dropdown",
					'Options' => array
					(
					)
				),

				'ipv4' => array
				(
					'Type' => 'text',
					"FriendlyName" => "IPv4 Addresses",
					'Size' => '25',
					'Default' => '1',
				),

				'ipv6' => array
				(
					'Type' => 'text',
					"FriendlyName" => "IPv6 Addresses",
					'Size' => '25',
					'Default' => '0',
				),

				'internal' => array
				(
					"FriendlyName" => "Internal IP's",
					'Type' => 'yesno',
				),

				'quickbackup' => array
				(
					"FriendlyName" => "Quick Backup",
					'Type' => 'yesno',
				),

				'console' => array
				(
					"FriendlyName" => "Console/VNC Redirection",
					'Type' => 'yesno',
				),

				'tun' => array
				(
					"FriendlyName" => "TUN/TAP suport",
					'Type' => 'yesno',
				),

				'ppp' => array
				(
					"FriendlyName" => "PPP Support",
					'Type' => 'yesno',
					'Description' => 'Default PPP settings',
				),

			);

			return $options;
		}

	}

Add config options for server module

Add config options for server module


<?php

namespace mcordingley\Regression\Tests;

use mcordingley\Regression\Observation;
use PHPUnit_Framework_TestCase;

class ObservationTest extends PHPUnit_Framework_TestCase
{
    public function testGetters()
    {
        $observation = new Observation([1, 2], 3);

        static::assertEquals([1, 2], $observation->getFeatures());
        static::assertEquals(3, $observation->getOutcome());
    }
}

Make a test case for the Observation class.


<?php
/**
 * Plugin Name: Improv events & teams
 * Plugin URI: https://github.com/vatoz/wpimprov
 * Description: Will display events and teams
 * Version: 0.0.1
 * Author: Vaclav Cerny
 * Author URI: https://www.facebook.com/vaclav.cerny.12
 * License: MIT
 */

add_action( 'init', 'wpimprov_create_post_type' );

/*
Vytvoří taxonomii pro týmy a samotný typ zápisku tým
*/
function wpimprov_create_post_type() {
	register_taxonomy(
	'wpimprov_city',
	'wpimprov_team',
	array(
			'label' => __( 'City' ),
			//'rewrite' => array( 'slug' => 'city' ),
			'show_ui'           => true,
		'show_admin_column' => true,
		'hierarchical'=>true,
	)
	);

	register_post_type( 'wpimprov_team',
		array(
		'labels' => array(
			'name' => __( 'Teams' ),
			'singular_name' => __( 'Team' )
		),
		'taxonomies'=>array(
			'wpimprov_city'
			),
		"supports"=>array(
			"title",
			"editor",
			"thumbnail",
			"revisions",
			"custom-fields",
		),
		'public' => true,
		'has_archive' => true,
		)
	);
}

Add teams content type and associated city taxonomy


<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @since         3.0.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Console\Exception;

use Cake\Core\Exception\Exception;

/**
 * Used when a shell cannot be found.
 */
class MissingShellException extends Exception
{

    protected $_messageTemplate = 'Shell class for "%s" could not be found.';
}

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @since         3.0.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Console\Exception;

use Cake\Core\Exception\Exception;

/**
 * Used when a shell cannot be found.
 */
class MissingShellException extends Exception
{

    protected $_messageTemplate = 'Shell class for "%s" could not be found. If you are trying to use a plugin shell, that was loaded via $this->addPlugin(), you may need to update bin/cake.php to match https://github.com/cakephp/app/tree/master/bin/cake.php';
}

Improve error message for missing shells

Attempt to improve the missing shell error to cover the scenario when
someone is using a new style plugin but has an outdated bin/cake.php
that isn't using CommandRunner.

Refs markstory/asset_compress#324


<?php

namespace Owbaz\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class UserController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        return $this->render('OwbazUserBundle:Default:index.html.twig');
    }
}

Create User Controller in user bundle

Create User Controller in user bundle


<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('ensure that the tickets index works');
$I->amOnPage('/tickets');
$I->see('Title', 'th');
$I->see('Description', 'th');
$I->see('Priority', 'th');
$I->see('Owner', 'th');
$I->dontSee('whoops');

Add test for tickets index view

Add test for tickets index view


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * @package   Zend_Log
 */

namespace ZendTest\Log\Formatter;

use DateTime;
use ZendTest\Log\TestAsset\StringObject;
use Zend\Log\Formatter\Db as DbFormatter;

/**
 * @category   Zend
 * @package    Zend_Log
 * @subpackage UnitTests
 * @group      Zend_Log
 */
class DbTest extends \PHPUnit_Framework_TestCase
{
    public function testDefaultDateTimeFormat()
    {
        $formatter = new DbFormatter();
        $this->assertEquals(DbFormatter::DEFAULT_DATETIME_FORMAT, $formatter->getDateTimeFormat());
    }

    /**
     * @dataProvider provideDateTimeFormats
     */
    public function testSetDateTimeFormat($dateTimeFormat)
    {
        $formatter = new DbFormatter();
        $formatter->setDateTimeFormat($dateTimeFormat);

        $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat());
    }

    /**
     * @return array
     */
    public function provideDateTimeFormats()
    {
        return array(
            array('r'),
            array('U'),
            array(DateTime::RSS),
        );
    }

    /**
     * @dataProvider provideDateTimeFormats
     */
    public function testAllowsSpecifyingDateTimeFormatAsConstructorArgument($dateTimeFormat)
    {
        $formatter = new DbFormatter($dateTimeFormat);

        $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat());
    }

    public function testFormatDateTimeInEvent()
    {
        $datetime = new DateTime();
        $event = array('timestamp' => $datetime);
        $formatter = new DbFormatter();

        $format = DbFormatter::DEFAULT_DATETIME_FORMAT;
        $this->assertContains($datetime->format($format), $formatter->format($event));
    }
}

Add tests for the new DbFormatter

Add tests for the new DbFormatter

Each Formatter should be covered by unit tests.


<?php

declare(strict_types=1);

namespace App\Entity\Migration;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20221008043751 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Remove stations that were mis-created.';
    }

    public function up(Schema $schema): void
    {
        $this->addSql(
            <<<'SQL'
            DELETE
            FROM station
            WHERE media_storage_location_id IS NULL
              OR recordings_storage_location_id IS NULL
              OR podcasts_storage_location_id IS NULL
            SQL
        );
    }

    public function down(Schema $schema): void
    {
        // Noop
    }
}

Create DB migration to auto-remove mis-created stations.


<?php

$instance_sub_table = new Table("cc_configuration", "configuration_key as cfgkey, configuration_value as cfgvalue");
$DBHandle  = DbConnect();
$configuration_query = $instance_sub_table -> Get_list($DBHandle);

foreach ($configuration_query as $configuration)
{
    define($configuration['cfgkey'], $configuration['cfgvalue']);
}

?>

UPDATE : missing file in repo

UPDATE : missing file in repo

git-svn-id: d2ca001274ea5b586d14e99f1302c6041fd0d671@583 9d51a8f0-6521-42ea-932e-d822aa02ce2f


<?php

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

class AlterTableAccountAddStatusColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('account', function (Blueprint $table) {
            $table->unsignedTinyInteger('status')->default('1')->after('amount');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('account', function (Blueprint $table) {
            $table->dropColumn('status');
        });
    }
}

Add status column for accounts

Add status column for accounts


<?php

/**
 * This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
 * The license and all terms en conditions that apply to Stippers also apply to this file.
 *
 * @author Stan Wijckmans
 *
 * Runnable to send a summary of the balance on user accounts to the receivers set in config.
 */

require_once __DIR__.'/../IRunnable.php';

require_once __DIR__.'/../../config/WeeklyWinnerConfig.php';

require_once __DIR__.'/../../models/membership/MembershipDB.php';
require_once __DIR__.'/../../models/membership/MembershipDBException.php';

require_once __DIR__.'/../../models/weeklyWinner/WeeklyWinnerDB.php';
require_once __DIR__.'/../../models/weeklyWinner/WeeklyWinnerDBException.php';

abstract class WeeklyWinnerPicker implements IRunnable {

    public static function run() {
        try {
            //Get list of user IDs of users that are a member this year
            $userIds = MembershipDB::getUserIdsThisYear();
            //Get list of last N winners
            $lastWinners = WeeklyWinnerDB::getLastNWinners(WeeklyWinnerConfig::MIN_WINNING_INTERVAL);

            //Get list of user IDs that have not won the last N times
            if ($lastWinners)
                $possibleWinners = array_diff($userIds, $lastWinners);
            else
                $possibleWinners = $userIds;

            //Pick a random user ID
            $winnerIdx = rand(0, count($possibleWinners) - 1);

            //Add chosen user ID as winner
            WeeklyWinnerDB::addWeeklyWinner($possibleWinners[$winnerIdx]);
        }
        catch (Exception $ex) {
            var_dump($ex);
        }
    }
}

Add runnable to generate winner.

Add runnable to generate winner.


<?php
/**
 * @package api
 * @subpackage objects
 */
class KalturaMediaServerStatus extends KalturaObject
{
	private static $mapBetweenObjects = array
	(
	);

	/* (non-PHPdoc)
	 * @see KalturaObject::getMapBetweenObjects()
	 */
	public function getMapBetweenObjects()
	{
		return array_merge(parent::getMapBetweenObjects(), self::$mapBetweenObjects);
	}
}

Enable media servers to report status

Enable media servers to report status


#!/usr/local/bin/php -q
<?php

$last_text = "";

while(!stristr($status, "Done")) {
        $status = get_status();
        if($status <> "") {
                echo $status . "\n";
        }
        sleep(1);
}

function get_status() {
        global $last_text;
        $status = file_get_contents("/var/run/filter_reload_status");
        $status = str_replace("...", "", $status);
        $status .= "...";
        if($status <> $last_text) {
                $last_text = $status;
                return $status;
        }
        return "";
}

?>

Add console application which shows the filter reloading status


<?php

namespace Enzyme\Axiom\Atoms;

use Enzyme\Axiom\Exceptions\AtomException;

class StringAtom implements AtomInterface
{
    protected $value;

    public function __construct($value)
    {
        if (is_string($value) === false || strlen($value) < 1) {
            throw new AtomException(get_class(), $value);
        }

        $this->value = (int) $value;
    }

    public function getValue()
    {
        return $this->value;
    }
}

Add new String atom type.

Add new String atom type.


<?php
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Bruno P. Kinoshita, Peter Florijn
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

namespace Entities;

use Nestor\Entities\TestCases;
use \TestCase;

class TestCasesTest extends TestCase
{

    public function setUp() {
        parent::setUp();
        $this->createApplication();
    }

    public function testClassAttributes() {
        $fillable = ['project_id', 'test_suite_id'];
        $hidden = [];

        $testCases = new TestCases();
        $this->assertEmpty(array_diff($fillable, $testCases->getFillable()));

        $this->assertEmpty(array_diff($hidden, $testCases->getHidden()));
    }
}

Add tests for test cases

Add tests for test cases


<?php

namespace libphonenumber\Tests\Issues;

use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberToTimeZonesMapper;
use libphonenumber\PhoneNumberUtil;

/**
 * Test that an extra not operator is messing up timezone lookup
 * @see https://github.com/giggsey/libphonenumber-for-php/issues/159
 * @package libphonenumber\Tests\Issues
 */
class Issue159Test extends \PHPUnit_Framework_TestCase
{
    const LOS_ANGELES_TZ = "America/Los_Angeles";

    public function setUp()
    {
        // Reset instance each time
        PhoneNumberUtil::resetInstance();
    }

    public function testLookupTZ_LA()
    {
        $number = new PhoneNumber();
        $number->setCountryCode(1)->setNationalNumber(2082924565);

        $timeZoneMapper = PhoneNumberToTimeZonesMapper::getInstance();

        $this->assertEquals(array(self::LOS_ANGELES_TZ), $timeZoneMapper->getTimeZonesForNumber($number));
    }
}

Add test to show problem and how it is fixed.


<?php

namespace Frankkessler\Guzzle\Oauth2\Tests;

use Frankkessler\Guzzle\Oauth2\AccessToken;
use Frankkessler\Guzzle\Oauth2\GrantType\ClientCredentials;
use Frankkessler\Guzzle\Oauth2\GrantType\RefreshToken;
use Frankkessler\Guzzle\Oauth2\Oauth2Client;
use Frankkessler\Guzzle\Oauth2\Tests\GuzzleServer;
use Frankkessler\Guzzle\Oauth2\Tests\MockResponses;
use Frankkessler\Guzzle\Oauth2\Utilities;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

class UtilitiesTest extends \Mockery\Adapter\Phpunit\MockeryTestCase
{
   public function testClientUsesRefreshTokenOnClientRequest()
    {
        $callback_url = 'https://www.test.com/oauth/callback';

        $authorization_url = Utilities::getAuthorizationUrl('https://www.test.com',[
            'client_id'     => 'test_client_id',
            'scope'         => '',
            'redirect_uri'  => $callback_url,
        ]);

        $this->assertEquals('https://www.test.com?response_type=code&access_type=offline&client_id=test_client_id&redirect_uri='.urlencode($callback_url).'&scope=', $authorization_url);
    }
}

Add authorization url helper test

Add authorization url helper test


<?php

namespace H4D\Leveret\Validation;

interface ConstraintInterface
{

    /**
     * @param mixed $value
     *
     * @return bool
     */
    public function validate($value);

    /**
     * @return array
     */
    public function getViolations();

}

Add new interface for constraints.

Add new interface for constraints.


<?php

namespace Alchemy\Zippy\Tests\Resource;

use Alchemy\Zippy\Resource\Resource;
use Alchemy\Zippy\Tests\TestCase;

class ResourceTest extends TestCase
{
    /**
     * @covers Alchemy\Zippy\Resource\Resource::__construct
     * @covers Alchemy\Zippy\Resource\Resource::getTarget
     * @covers Alchemy\Zippy\Resource\Resource::getOriginal
     */
    public function testGetTargetAndOriginal()
    {
        $original = 'original-style';
        $target = 'target-fishnet';

        $resource = new Resource($original, $target);

        $this->assertEquals($original, $resource->getOriginal());
        $this->assertEquals($target, $resource->getTarget());
    }

    /**
     * @covers Alchemy\Zippy\Resource\Resource::canBeProcessedInPlace
     * @dataProvider provideProcessInPlaceData
     */
    public function testCanBeProcessedInPlace($expected, $context, $original, $target)
    {
        $resource = new Resource($original, $target);

        $this->assertInternalType('boolean', $resource->canBeProcessedInPlace($context));
        $this->assertEquals($expected, $resource->canBeProcessedInPlace($context));
    }

    public function provideProcessInPlaceData()
    {
        return array(
            array(true, '/path/to', '/path/to/file1', 'file1'),
            array(false, '/path/to', '/path/file1', 'file1'),
            array(true, '/path', '/path/to/file1', 'to/file1'),
            array(true, '/path/to', '/path/to/subdir/file2', 'subdir/file2'),
        );
    }
}

Add unit tests for Resource

Add unit tests for Resource


<?php

namespace Concrete\Core\Foundation\Environment;

class User
{
    /**
     * @var FunctionInspector
     */
    protected $functionInspector;

    /**
     * @param FunctionInspector $functionInspector
     */
    public function __construct(FunctionInspector $functionInspector)
    {
        $this->functionInspector = $functionInspector;
    }

    /**
     * Check if the current user is root/superuser.
     *
     * @return bool|null return true if the current user is root, false if not root, or NULL if we don't know
     */
    public function isSuperUser()
    {
        $result = null;
        if ($result === null && $this->functionInspector->functionAvailable('posix_getuid')) {
            $uid = posix_getuid();
            if (is_int($uid)) {
                $result = $uid === 0;
            }
        }

        return $result;
    }
}

Add a helper to check if the current user is root


<?php
/**
 * DatabaseConnectionException class
 *
 * Type of exception thrown when ResqueStat can not connect
 * to a database
 *
 * @subpackage      resqueboard.lib
 * @since            1.0.0
 * @author           Wan Qi Chen <kami@kamisama.me>
 */

namespace ResqueBoard\Lib;

class DatabaseConnectionException extends \Exception
{
}

Move exception class to its own file

Move exception class to its own file


<?php

namespace App\Model;

class SQLServerModelExample extends \Pleets\Sql\AbstractionModel
{
    public function consulta()
    {
        $sql = "SELECT * FROM SYS.TABLES";
        $result = $this->getDb()->query($sql);
        return $this->getDb()->toArray(array('encode_utf8' => true));
    }
}

Fix name of file SQLServerModel

Fix name of file SQLServerModel


<?php

namespace ZfcRbacTest\Controller;

use PHPUnit_Framework_TestCase;
use ZfcRbac\Firewall\Controller as ControllerFirewall;

class ControllerTest extends PHPUnit_Framework_TestCase
{
    public function getControllerFirewallParameters()
    {
        return array(
            array(
                array(
                    'rules' => array(
                        'controller' => 'IndexController',
                        'actions'    => 'foo',
                        'roles'      => 'guest'
                    )
                ),
                array(
                    array(
                        'resource' => 'IndexController:foo',
                        'result'   => true
                    ),
                    array(
                        'resource' => 'IndexController:bar',
                        'result'   => false
                    ),
                )
            ),

            array(
                array(
                    'rules' => array(
                        'controller' => 'IndexController',
                        'actions'    => array('foo', 'bar'),
                        'roles'      => 'guest'
                    )
                ),
                array(
                    array(
                        'resource' => 'IndexController:foo',
                        'result'   => true
                    ),
                    array(
                        'resource' => 'IndexController:bar',
                        'result'   => true
                    ),
                    array(
                        'resource' => 'IndexController:baz',
                        'result'   => false
                    ),
                )
            ),

            array(
                array(
                    'rules' => array(
                        'controller' => 'IndexController',
                        'actions'    => array('foo', 'bar'),
                        'roles'      => array('guest')
                    )
                ),
                array(
                    array(
                        'resource' => 'IndexController:foo',
                        'result'   => true
                    ),
                    array(
                        'resource' => 'IndexController:bar',
                        'result'   => true
                    ),
                    array(
                        'resource' => 'IndexController:baz',
                        'result'   => false
                    ),
                )
            )
        );
    }

    /**
     * @dataProvider getControllerFirewallParameters
     */
    public function testControllerFirewall($rules, $checks)
    {
        $firewall = new ControllerFirewall($rules);
        $mockRbac = $this->getMock('ZfcRbac\Service\Rbac');
        $mockRbac->expects($this->any())
                 ->method('hasRole')
                 ->will($this->returnCallback(function($val) {
            if ($val === array('guest')) {
                return true;
            }

            return false;
        }));

        $firewall->setRbac($mockRbac);

        foreach ($checks as $check) {

            $this->assertEquals($check['result'], $firewall->isGranted($check['resource']));
        }
    }
}

Add tests for Controller firewall

Add tests for Controller firewall


<?php
declare(strict_types=1);

namespace Fc2blog\Tests\App\Controller\Admin\Files;

use Fc2blog\Config;
use Fc2blog\Model\FilesModel;
use Fc2blog\Tests\DBHelper;
use Fc2blog\Tests\Helper\ClientTrait;
use Fc2blog\Web\Controller\Admin\FilesController;
use Fc2blog\Web\Request;
use Fc2blog\Web\Session;
use PHPUnit\Framework\TestCase;

class AjaxDeleteTest extends TestCase
{
  use ClientTrait;

  public function setUp(): void
  {
    DBHelper::clearDbAndInsertFixture();
    Config::set("DEBUG", false);
    parent::setUp();
  }

  public function testAjaxMultiDelete(): void
  {
    Session::destroy(new Request());
    $this->resetSession();
    $this->resetCookie();
    $this->mergeAdminSession();

    $ut = new UploadTest();
    $ut->uploadFile();
    $ut->uploadFile();
    $ut->uploadFile();

    // get sig(CSRF Token) and entries
    // admin/files/uploadはガワの部分（アップロードフォームまで）
    $c = $this->reqGet("/admin/files/upload");
    $this->assertInstanceOf(FilesController::class, $c);
    $sig = $this->clientTraitSession['sig'];

    $fm = new FilesModel();
    $before_files = $fm->find('all');
//    var_dump($before_files);
    $before_files_count = count($before_files);

    $delete_file_id_list = [];
    foreach($before_files as $before_file){
      $delete_file_id_list[] = $before_file['id'];
    }
    $will_be_delete_files_count = count($delete_file_id_list);

    $c = $this->reqPost("/admin/files/ajax_delete", ['id' => $delete_file_id_list, 'sig' => $sig]);

    $this->assertEquals(0/*success*/, $c->get('json')['status']);

//    var_dump($c);

    $after_files = $fm->find('all');
//    var_dump($after_files);
    $this->assertCount($before_files_count - $will_be_delete_files_count, $after_files);
  }
}

Add test: /admin/files/ajax_delete multi file delete.


<?php

namespace Theodo\SendGridMailerBundle\Mailer;

use SendGrid as SendGridService;
use SendGrid\Email;

/**
 * Send emails via the sendGridMailer API
 * Different methods can be used depending on the use case
 *
 * @author Reynald Mandel <reynaldm@theodo.fr>
 */
class SendGridMailer
{
    /**
     * @var SendGridService
     */
    protected $sendGridService;

    /**
     * @param string $sendGridUserLogin     the send grid user's account login
     * @param string $sendGridUserPassword  the send grid user's account password
     */
    public function __construct($sendGridUserLogin, $sendGridUserPassword)
    {
        $this->sendGridService = new SendGridService($sendGridUserLogin, $sendGridUserPassword, array("turn_off_ssl_verification" => true));
    }

    /**
     * Send an already fully prepared email
     * Return true if the mail has been effectively sent, false otherwise
     *
     * @param Email $email
     * @return bool
     */
    public function sendEmail(Email $email)
    {
        $response = $this->sendGridService->send($email);

        return $response->message == 'success';
    }
}

Add a basic version of send grid mailer

Add a basic version of send grid mailer


<?php

namespace HydrefLab\SWAPI;

use ReflectionClass;

class Mapper
{
    /**
     * @param object $data
     * @param string|object $className
     * @return object
     */
    public function map($data, $className)
    {
        if (true === is_object($className)) {
            $className = get_class($className);
        }

        $rc = new ReflectionClass($className);

        // @TODO: iterate on object properties and assign data
        // @TODO: map snake_case data to camelCase properties
        // @TODO: use shallow/deep mapping?
        // @TODO: recursive

        return $rc->newInstanceWithoutConstructor();
    }
}

Add concept class of data mapper

Add concept class of data mapper


<?php
/**
 * contentinum - accessibility websites
 *
 * LICENSE
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category contentinum components
 * @package Filter
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 * @copyright Copyright (c) 2009-2013 jochum-mediaservices, Katja Jochum (http://www.jochum-mediaservices.de)
 * @license http://www.opensource.org/licenses/bsd-license
 * @since contentinum version 5.0
 * @link      https://github.com/Mikel1961/contentinum-components
 * @version   1.0.0
 */
namespace Contentinum\Entity\Exeption;

/**
 * Class method not exists or not found
 * @author mike
 *
 */
class IsPublishEntityException extends \InvalidArgumentException
{
}

Add entry is publish exception

Add entry is publish exception

Change-Id: I7eb08b9a03c18054e3bf2069a07679b089b0f5bf


<?php

namespace Askaoru\Routable\Http;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class RoutableKernel extends HttpKernel
{
    /**
     * Start the kernel instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function __construct(Application $app, Router $router)
    {
        $this->checkLocale();
        parent::__construct($app, $router);
    }

    /**
     * Determine whether or not the locale should be filtered.
     *
     * @return void
     */
    public function checkLocale()
    {
        $config = [
            'enable_locale_append' => false,
            'enabled_locales' => [],
        ];

        if (file_exists($config_file = base_path('config/routable.php'))) {
            $config = include $config_file;
        }

        if (!$config['enable_locale_append']) {
            return;
        }

        $request_segments = explode('/', $_SERVER['REQUEST_URI']);
        $intersect = array_intersect($request_segments, $config['enabled_locales']);

        if ($intersect) {
            $locale = array_values($intersect)[0];
            $this->filterAndDefineLocale($locale, $request_segments);
        }
    }

    /**
     * Filter the locale from the request uri and define it globally.
     *
     * @param  string $locale
     * @param  array $request_segments
     * @return void
     */
    public function filterAndDefineLocale($locale, $request_segments)
    {
        // Let's get the project base path segments and compare it with the request segments.
        $base_path_segments = explode('/', str_replace('index.php', '', $_SERVER['PHP_SELF']));
        $base_and_request_comparison = array_diff($request_segments, $base_path_segments);

        // Remove the locale from the base and request segments comparison result.
        $locale_removed = array_diff($base_and_request_comparison, [$locale]);

        // Rebuild the resulting array with the original project base path segments.
        $uri_segments = array_merge($base_path_segments, $locale_removed);
        $uri = implode('/', $uri_segments);

        // Set the new uri and define the locale globally so we can pick it up later.
        $_SERVER['REQUEST_URI'] = $uri;

        define('ROUTABLE_LOCALE', $locale);
    }
}

Add a kernel to handle multilingual routing


<?php

namespace Doctrine\Tests\Common\Annotations;

use Doctrine\Common\Annotations\Annotation;
use PHPUnit\Framework\TestCase;

final class AnnotationTest extends TestCase
{
    public function testMagicGetThrowsBadMethodCallException()
    {
        $name = 'foo';

        $annotation = new Annotation([]);

        $this->expectException(\BadMethodCallException::class);
        $this->expectExceptionMessage(sprintf(
            "Unknown property '%s' on annotation '%s'.",
            $name,
            Annotation::class
        ));

        $annotation->{$name};
    }

    public function testMagicSetThrowsBadMethodCallException()
    {
        $name = 'foo';

        $annotation = new Annotation([]);

        $this->expectException(\BadMethodCallException::class);
        $this->expectExceptionMessage(sprintf(
            "Unknown property '%s' on annotation '%s'.",
            $name,
            Annotation::class
        ));

        $annotation->{$name} = 9001;
    }
}

Add test for __get() and __set()

Fix: Add test for __get() and __set()


<?php
/**
 * Copyright (c) 2012-2013 Jurian Sluiman.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *   * Neither the names of the copyright holders nor the names of the
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @package     SlmException
 * @author      Jurian Sluiman <jurian@juriansluiman.nl>
 * @copyright   2012-2013 Jurian Sluiman http://juriansluiman.nl.
 * @license     http://www.opensource.org/licenses/bsd-license.php  BSD License
 */

namespace SlmException\Exception;

interface ServerErrorInterface extends ExceptionInterface
{}

Add ServerError as exception marker

Add ServerError as exception marker


<?php namespace TypiCMS;

trait NestableTrait
{
    /**
     * Return a custom nested collection
     *
     * @param  array            $models
     * @return NestedCollection
     */
    public function newCollection(array $models = array())
    {
        return new NestableCollection($models);
    }
}

Add trait to add the custom nested collection class


<?php

use Illuminate\Database\Migrations\Migration;

class JsonNewsPostPage extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // DBAL (2.10.0) can't migrate to JSON datatype.
        // It only creates TEXT with DC2Type:json as comment.
        DB::statement('ALTER TABLE news_posts MODIFY page JSON');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // DBAL (2.10.0) can't migrate from JSON datatype.
        // It explodes at unrecognized JSON datatype.
        DB::statement('ALTER TABLE news_posts MODIFY page TEXT');
    }
}

Use JSON datatype for news page

Use JSON datatype for news page


<?php

namespace Bolt\Provider;

use Bolt\TemplateChooser;
use Silex\Application;
use Silex\ServiceProviderInterface;

class TemplateChooserServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['templatechooser'] = $app->share(
            function ($app) {
                $omnisearch = new TemplateChooser($app);

                return $omnisearch;
            }
        );

    }

    public function boot(Application $app)
    {
    }
}

<?php

namespace Bolt\Provider;

use Bolt\TemplateChooser;
use Silex\Application;
use Silex\ServiceProviderInterface;

class TemplateChooserServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['templatechooser'] = $app->share(
            function ($app) {
                $chooser = new TemplateChooser($app);

                return $chooser;
            }
        );

    }

    public function boot(Application $app)
    {
    }
}

Correct variable name from copy/pasta

Correct variable name from copy/pasta


<?php

use Hubzero\Content\Migration\Base;

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

/**
 * Migration script for adding key to recaptcha
 **/
class Migration20150107022822PlgHubzeroRecaptcha extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		$params = array(
			'private' => '6Lf9IgATAAAAAAs_fYlomzK_HO6gbUVpSkGkDTRl',
			'public'  => '6Lf9IgATAAAAAAl3WEw0hwpbsG9O2_EXY_-NH7xd'
		);

		$this->savePluginParams('hubzero','recaptcha', $params);
	}
}

[PLG_HUBZERO_RECAPTCHA] Add master key to plugin params since all hubs use same key.


<?php

namespace spec\PhpSpec\Wrapper;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

use PhpSpec\Wrapper\Wrapper;
use PhpSpec\Wrapper\Subject\WrappedObject;
use PhpSpec\Wrapper\Subject\Caller;
use PhpSpec\Wrapper\Subject\SubjectWithArrayAccess;
use PhpSpec\Wrapper\Subject\ExpectationFactory;
use PhpSpec\Wrapper\Subject\Expectation\ExpectationInterface;

class SubjectSpec extends ObjectBehavior
{
    function let(Wrapper $wrapper, WrappedObject $wrappedObject, Caller $caller,
                 SubjectWithArrayAccess $arrayAccess, ExpectationFactory $expectationFactory)
    {
        $this->beConstructedWith(null, $wrapper, $wrappedObject, $caller, $arrayAccess, $expectationFactory);
    }

    function it_passes_the_created_subject_to_expectation(WrappedObject $wrappedObject,
        ExpectationFactory $expectationFactory, ExpectationInterface $expectation)
    {
        $expectation->match(Argument::cetera())->willReturn(true);
        $wrappedObject->getClassName()->willReturn('spec\PhpSpec\Wrapper\Everything');
        $expectationFactory->create(Argument::cetera())->willReturn($expectation);

        $this->callOnWrappedObject('shouldBeAlright');
        $expectationFactory->create(Argument::any(), Argument::type('spec\PhpSpec\Wrapper\Everything'), Argument::any())->shouldHaveBeenCalled();
    }

    function it_passes_the_existing_subject_to_expectation(Wrapper $wrapper, WrappedObject $wrappedObject, Caller $caller,
        SubjectWithArrayAccess $arrayAccess, ExpectationFactory $expectationFactory, ExpectationInterface $expectation)
    {
        $existingSubject = new \ArrayObject;
        $this->beConstructedWith($existingSubject, $wrapper, $wrappedObject, $caller, $arrayAccess, $expectationFactory);

        $expectation->match(Argument::cetera())->willReturn(true);
        $wrappedObject->getClassName()->willReturn('\ArrayObject');
        $expectationFactory->create(Argument::cetera())->willReturn($expectation);

        $this->callOnWrappedObject('shouldBeAlright');
        $expectationFactory->create(Argument::any(), Argument::exact($existingSubject), Argument::any())->shouldHaveBeenCalled();
    }
}

class Everything
{
    public function isAlright()
    {
        return true;
    }
}

Add specs for regression on the expectation factory issue


<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Sort an array in reverse order

Sort an array in reverse order


<?php

namespace ModuleGenerator\Module;

use ModuleGenerator\CLI\Service\Generate\GeneratableFile;
use ModuleGenerator\PhpGenerator\ModuleName\ModuleName;

abstract class GeneratableModuleFile extends GeneratableFile
{
    /** @var ModuleName */
    private $moduleName;

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

    final public function getModuleName(): ModuleName
    {
        return $this->moduleName;
    }

    final protected function getFrontendModulePath(string $filePath = null): string
    {
        if ($filePath === null) {
            return 'Frontend/Modules/' . $this->getModuleName();
        }

        return $this->getFrontendModulePath() . '/' . $filePath;
    }

    final protected function getBackendModulePath(string $filePath = null): string
    {
        if ($filePath === null) {
            return 'Backend/Modules/' . $this->getModuleName();
        }

        return $this->getBackendModulePath() . '/' . $filePath;
    }
}

Add base class for all module files

Add base class for all module files


<?php

require_once(dirname(__FILE__).'/../bootstrap/common.php');
sfContext::createInstance($configuration);

$viti =  CompteTagsView::getInstance()->findOneCompteByTag('test', 'test_teledeclaration')->getEtablissement();

$t = new lime_test(1);

$operation = 'COVID';

$subvention = SubventionClient::getInstance()->createOrFind($viti->identifiant, $operation);

$t->is($subvention->_id, 'SUBVENTION-'.$viti->identifiant.'-'.$operation, 'id de document généré');

Test unitaire pour les subventions

Test unitaire pour les subventions


<?php

declare(strict_types=1);

namespace Keboola\Test\Backend\Redshift;

use Keboola\Csv\CsvFile;
use Keboola\StorageApi\ClientException;
use Keboola\Test\StorageApiTestCase;

class FulltextSearchTest extends StorageApiTestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->_initEmptyTestBuckets();
    }

    public function testForbiddenWhereOperators()
    {
        $csvFile = new CsvFile(tempnam(sys_get_temp_dir(), 'keboola'));
        $csvFile->writeRow(['test']);
        $tableId = $this->_client->createTable($this->getTestBucketId(), 'conditions', $csvFile);

        $this->expectException(ClientException::class);
        $this->expectExceptionMessage('Fulltext search is not supported for Redshift backend.');
        $this->_client->getTableDataPreview($tableId, ['fulltextSearch' => 'not-supported']);
    }
}

Add tests for forbidden fulltext search on RS backend