<?php

declare(strict_types=1);

namespace Cortex\Fort\Console\Commands;

use Rinvex\Fort\Console\Commands\SeedCommand as BaseSeedCommand;

class SeedCommand extends BaseSeedCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:seed:fort';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed Cortex Fort Data.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        parent::handle();

        $this->seedResources(app('rinvex.fort.role'), realpath(__DIR__.'/../../../resources/data/roles.json'), ['name', 'description']);
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Fort\Console\Commands;

use Rinvex\Fort\Console\Commands\SeedCommand as BaseSeedCommand;

class SeedCommand extends BaseSeedCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cortex:seed:fort';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Seed Cortex Fort Data.';
}

Move tenant role seeding to cortex/tenants module


<?php

namespace MusicBrainz\Filter\Accessor;
use MusicBrainz\Filter\Filter;

/**
 * Provides accessors for the alias name
 */
trait AliasNameAccessorTrait
{
    use AccessorTrait;

    /**
     * Returns the alias.
     *
     * @return null|string
     */
    public function getAliasName(): ?string
    {
        return $this->getFilterValue('alias');
    }

    /**
     * Sets an alias.
     *
     * @param null|string $aliasName An alias
     *
     * @return Filter
     */
    public function setAliasName(?string $aliasName): Filter
    {
        return $this->setFilterValue('alias', $aliasName);
    }
}

<?php

namespace MusicBrainz\Filter\Accessor;

/**
 * Provides accessors for the alias name
 */
trait AliasNameAccessorTrait
{
    use AccessorTrait;

    /**
     * Returns the alias.
     *
     * @return null|string
     */
    public function getAliasName(): ?string
    {
        return $this->getFilterValue('alias');
    }

    /**
     * Sets an alias.
     *
     * @param null|string $aliasName An alias
     *
     * @return self
     */
    public function setAliasName(?string $aliasName): self
    {
        return $this->setFilterValue('alias', $aliasName);
    }
}

Use 'self' as return type in accessor trait.


<?php

// skip conditions
$skipped = true;
if (!static::tableExists('people')) {
    printf("Skipping migration because table `people` does not exist yet\n");
    return static::STATUS_SKIPPED;
}

// migration
if (static::getColumn('people', 'Phone')) {
    print("Altering length of field `Phone` on table `people`'\n");
    DB::nonQuery("ALTER TABLE `people` CHANGE COLUMN `Phone` `Phone` DECIMAL(15) UNSIGNED NULL DEFAULT NULL  COMMENT '' AFTER `Email`;");
    $skipped = false;
}

if (!static::getColumn('history_people', 'CustomerEmailRedirect')) {
    print("Altering length of field `Phone` on table `history_people`'\n");
    DB::nonQuery("ALTER TABLE `history_people` CHANGE COLUMN `Phone` `Phone` DECIMAL(15) UNSIGNED NULL DEFAULT NULL  COMMENT '' AFTER `Email`;");
    $skipped = false;
}

// done
return $skipped ? static::STATUS_SKIPPED : static::STATUS_EXECUTED;

<?php

// skip conditions
$skipped = true;
if (!static::tableExists('people')) {
    printf("Skipping migration because table `people` does not exist yet\n");
    return static::STATUS_SKIPPED;
}

// migration
if (static::getColumn('people', 'Phone') && static::getColumnType('people', 'Phone') !== 'decimal(15,0) unsigned') {
    print("Altering length of field `Phone` on table `people`\n");
    DB::nonQuery("ALTER TABLE `people` CHANGE COLUMN `Phone` `Phone` DECIMAL(15) UNSIGNED NULL DEFAULT NULL  COMMENT '' AFTER `Email`;");
    $skipped = false;
}

if (static::getColumn('history_people', 'Phone') && static::getColumnType('history_people', 'Phone') !== 'decimal(15,0) unsigned') {
    print("Altering length of field `Phone` on table `history_people`\n");
    DB::nonQuery("ALTER TABLE `history_people` CHANGE COLUMN `Phone` `Phone` DECIMAL(15) UNSIGNED NULL DEFAULT NULL  COMMENT '' AFTER `Email`;");
    $skipped = false;
}

// done
return $skipped ? static::STATUS_SKIPPED : static::STATUS_EXECUTED;

Add decimal length condition to phone migration


<?php
class Kwc_Basic_Table_Trl_RowData extends Kwf_Model_Db_Row
{
    public function getReplacedContent($field)
    {
        return Kwc_Basic_Table_RowData::replaceContent($this->$field);
    }

    public function __get($name)
    {
        $value = parent::__get($name);
        if (!$value) {
            //FIXME load from master-row
        }
        return $value;
    }
}

<?php
class Kwc_Basic_Table_Trl_RowData extends Kwf_Model_Db_Row
{
    public function __get($name)
    {
        if ($name == 'id') {
            $value = parent::__get('master_id');
        } else {
            $value = parent::__get($name);
        }
        return $value;
    }
}

Remove unused function, return correct id

If id is requested master_id is needed


<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'jerome.lachaud@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'zbeekman@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@izaakbeekman.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

Set my email address from contact form

Set my email address from contact form


<?php

namespace Dock\Doctor\Action;

use Dock\Docker\Machine\Machine;
use Dock\Docker\Machine\MachineException;
use Dock\Installer\DockerInstaller;
use Dock\Installer\Installable;

class StartMachineOrInstall implements Installable
{
    /**
     * @var Machine
     */
    private $machine;

    /**
     * @var DockerInstaller
     */
    private $dockerInstaller;

    /**
     * @param Machine         $machine
     * @param DockerInstaller $dockerInstaller
     */
    public function __construct(Machine $machine, DockerInstaller $dockerInstaller)
    {
        $this->machine = $machine;
        $this->dockerInstaller = $dockerInstaller;
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        try {
            $this->machine->start();
        } catch (MachineException $e) {
        }

        if (!$this->machine->isRunning()) {
            $this->dockerInstaller->run();
        }
    }
}

<?php

namespace Dock\Doctor\Action;

use Dock\Docker\Machine\Machine;
use Dock\Docker\Machine\MachineException;
use Dock\Installer\DockerInstaller;
use Dock\Installer\Installable;

class StartMachineOrInstall implements Installable
{
    /**
     * @var Machine
     */
    private $machine;

    /**
     * @var DockerInstaller
     */
    private $dockerInstaller;

    /**
     * @param Machine         $machine
     * @param DockerInstaller $dockerInstaller
     */
    public function __construct(Machine $machine, DockerInstaller $dockerInstaller)
    {
        $this->machine = $machine;
        $this->dockerInstaller = $dockerInstaller;
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        try {
            $this->machine->start();
        } catch (MachineException $e) {
            // Ignore the problem as if the machine is not running, we
            // will run the installer.
        }

        if (!$this->machine->isRunning()) {
            $this->dockerInstaller->run();
        }
    }
}

Add comment about why catching this error without handling it


<?php
/*
 * Copyright (c) Ouzo contributors, http://ouzoframework.org
 * This file is made available under the MIT License (view the LICENSE file for more information).
 */
namespace Ouzo\Tests;

class MockDownloadHandler
{
    private $_fileName;

    public function downloadFile($fileData)
    {
        $this->_fileName = $fileData['label'];
        return $this;
    }

    public function streamMediaFile(array $fileData)
    {
        $this->_fileName = $fileData['label'];
        return $this;
    }

    public function getFileName()
    {
        return $this->_fileName;
    }
}

<?php
/*
 * Copyright (c) Ouzo contributors, http://ouzoframework.org
 * This file is made available under the MIT License (view the LICENSE file for more information).
 */

namespace Ouzo\Tests;

use Ouzo\Utilities\Arrays;

class MockDownloadHandler
{
    private $fileData;

    public function downloadFile($fileData)
    {
        $this->fileData = $fileData;
        return $this;
    }

    public function streamMediaFile(array $fileData)
    {
        $this->fileData = $fileData;
        return $this;
    }

    public function getFileName()
    {
        return Arrays::getValue($this->fileData, 'label');
    }

    public function getFileData()
    {
        return Arrays::getValue($this->fileData, 'data');
    }
}

Store complete data object inside mock.

Store complete data object inside mock.


<?php
declare(strict_types=1);

/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         3.2.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Routing\Exception;

use Cake\Core\Exception\Exception;

/**
 * An exception subclass used by the routing layer to indicate
 * that a route has resolved to a redirect.
 *
 * The URL and status code are provided as constructor arguments.
 *
 * ```
 * throw new RedirectException('http://example.com/some/path', 301);
 * ```
 *
 * If you need a more general purpose redirect exception use
 * Cake\Http\Exception\RedirectException instead of this class.
 */
class RedirectException extends Exception
{
    /**
     * @inheritDoc
     */
    protected $_defaultCode = 302;
}

<?php
declare(strict_types=1);

/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link          https://cakephp.org CakePHP(tm) Project
 * @since         3.2.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 */
namespace Cake\Routing\Exception;

use Cake\Core\Exception\Exception;

/**
 * An exception subclass used by the routing layer to indicate
 * that a route has resolved to a redirect.
 *
 * The URL and status code are provided as constructor arguments.
 *
 * ```
 * throw new RedirectException('http://example.com/some/path', 301);
 * ```
 *
 * If you need a more general purpose redirect exception use
 * Cake\Http\Exception\RedirectException instead of this class.
 *
 * @deprecated 4.1.0 Use Cake\Http\Exception\RedirectException instead.
 */
class RedirectException extends Exception
{
    /**
     * @inheritDoc
     */
    protected $_defaultCode = 302;
}

Mark routing exception as deprecated.

Mark routing exception as deprecated.

I don't want to change RedirectRoute or RoutingMiddleware at this time
as I don't want to break compatibility over a small value change.


<?php

namespace Phug\Test\Parser\TokenHandler;

use Phug\Lexer;
use Phug\Lexer\Token\TagToken;
use Phug\Parser\State;
use Phug\Parser\TokenHandler\CommentTokenHandler;
use Phug\Test\AbstractParserTest;

/**
 * @coversDefaultClass Phug\Parser\TokenHandler\CommentTokenHandler
 */
class CommentTokenHandlerTest extends AbstractParserTest
{
    /**
     * @covers ::<public>
     */
    public function testHandleToken()
    {
        $this->assertNodes('// foo', [
            '[DocumentNode]',
            '  [CommentNode]',
            '    [TextNode]',
        ]);

        $this->assertNodes("//-\n  foo", [
            '[DocumentNode]',
            '  [CommentNode]',
            '    [TextNode]',
        ]);

        $documentNodes = $this->parser->parse('// foo')->getChildren();
        self::assertSame('foo', $documentNodes[0]->getChildren()[0]->getValue());

        $documentNodes = $this->parser->parse("//-\n  foo")->getChildren();
        self::assertSame("foo\n", $documentNodes[0]->getChildren()[0]->getValue());
    }

    /**
     * @covers                   ::<public>
     * @expectedException        \RuntimeException
     * @expectedExceptionMessage You can only pass comment tokens to this token handler
     */
    public function testHandleTokenTokenException()
    {
        $lexer = new Lexer();
        $state = new State($lexer->lex(''));
        $handler = new CommentTokenHandler();
        $handler->handleToken(new TagToken(), $state);
    }
}

<?php

namespace Phug\Test\Parser\TokenHandler;

use Phug\Lexer;
use Phug\Lexer\Token\TagToken;
use Phug\Parser\State;
use Phug\Parser\TokenHandler\CommentTokenHandler;
use Phug\Test\AbstractParserTest;

/**
 * @coversDefaultClass Phug\Parser\TokenHandler\CommentTokenHandler
 */
class CommentTokenHandlerTest extends AbstractParserTest
{
    /**
     * @covers ::<public>
     */
    public function testHandleToken()
    {
        $this->assertNodes('// foo', [
            '[DocumentNode]',
            '  [CommentNode]',
            '    [TextNode]',
        ]);

        $this->assertNodes("//-\n  foo", [
            '[DocumentNode]',
            '  [CommentNode]',
            '    [TextNode]',
        ]);

        $documentNodes = $this->parser->parse('// foo')->getChildren();
        self::assertSame(" foo\n", $documentNodes[0]->getChildren()[0]->getValue());

        $documentNodes = $this->parser->parse("//-\n  foo")->getChildren();
        self::assertSame("\n  foo\n", $documentNodes[0]->getChildren()[0]->getValue());
    }

    /**
     * @covers                   ::<public>
     * @expectedException        \RuntimeException
     * @expectedExceptionMessage You can only pass comment tokens to this token handler
     */
    public function testHandleTokenTokenException()
    {
        $lexer = new Lexer();
        $state = new State($lexer->lex(''));
        $handler = new CommentTokenHandler();
        $handler->handleToken(new TagToken(), $state);
    }
}

Update parser unit tests according to new comment block indent system


<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\UnitBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;

/**
 * Class UnitManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class UnitManagerTest extends AbstractManagerTestCase
{
    protected function get()
    {
        return $this->container->get('unit.manager');
    }
}

<?php
/*
 * WellCommerce Open-Source E-Commerce Platform
 *
 * This file is part of the WellCommerce package.
 *
 * (c) Adam Piotrowski <adam@wellcommerce.org>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code.
 */

namespace WellCommerce\Bundle\UnitBundle\Tests\Manager;

use WellCommerce\Bundle\CoreBundle\Test\Manager\AbstractManagerTestCase;
use WellCommerce\Bundle\DoctrineBundle\Manager\ManagerInterface;

/**
 * Class UnitManagerTest
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class UnitManagerTest extends AbstractManagerTestCase
{
    protected function get() : ManagerInterface
    {
        return $this->container->get('unit.manager');
    }
}

Return types in manager tests

Return types in manager tests


<?php

declare(strict_types=1);

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\Exporter\Tests\Source;

use PHPUnit\Framework\TestCase;
use Sonata\Exporter\Source\ChainSourceIterator;

class ChainSourceIteratorTest extends TestCase
{
    public function testIterator(): void
    {
        $source = $this->createMock('Sonata\Exporter\Source\SourceIteratorInterface');

        $iterator = new ChainSourceIterator([$source]);

        foreach ($iterator as $data) {
        }
    }
}

<?php

declare(strict_types=1);

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\Exporter\Tests\Source;

use PHPUnit\Framework\TestCase;
use Sonata\Exporter\Source\ChainSourceIterator;

class ChainSourceIteratorTest extends TestCase
{
    /**
     * @doesNotPerformAssertions
     */
    public function testIterator(): void
    {
        $source = $this->createMock('Sonata\Exporter\Source\SourceIteratorInterface');

        $iterator = new ChainSourceIterator([$source]);

        foreach ($iterator as $data) {
        }
    }
}

Mark lack of assertions as deliberate

Mark lack of assertions as deliberate


<?php

    use PHPUnit\Framework\TestCase;

    require_once '../Opbeat/client.php';

    class ClientTest extends TestCase {

        public function testGetErrorLevel() {
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_WARNING), 'warning');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_COMPILE_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_NOTICE), 'notice');
        }

    }

<?php

    use PHPUnit\Framework\TestCase;

    require_once realpath(dirname(__FILE__).'/../Opbeat/client.php');

    class ClientTest extends TestCase {

        public function testGetErrorLevel() {
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_WARNING), 'warning');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_COMPILE_ERROR), 'fatal');
            $this->assertEquals(Opbeat_Client::getErrorLevel(E_NOTICE), 'notice');
        }

    }

FIX wrong inclusion in test

FIX wrong inclusion in test


<?php

if(!isset($blq))
{
	require_once(MODULES_ROOT . 'barlesque/client.php');
	$blq = new Barlesque();
}
$blq->fetch();

echo '<!DOCTYPE html>';
echo '<html>';

echo '<head>';
$this->title();
echo $blq->head;
$this->links();
echo '<script>bbccookies._showPrompt = function() { return false; }</script>';
echo '</head>';

echo '<body>';

echo $blq->bodyfirst;

<?php

if(!isset($blq))
{
	require_once(MODULES_ROOT . 'barlesque/client.php');
	$blq = new Barlesque();
}
$blq->fetch();

$page_type = 'blq ' . @$page_type;

echo '<!DOCTYPE html>';
echo '<html>';

echo '<head>';
$this->title();
echo $blq->head;
$this->links();
if(isset($headExtra))
{
	echo $headExtra;
}
echo '<script>bbccookies._showPrompt = function() { return false; }</script>';
echo '</head>';

echo '<body class="' . _e($page_type) . '">';

echo $blq->bodyfirst;

Allow $page_type [body classes] to be specified, as well as $headExtra [contents transcluded into <head>]


<?php
/**
 * Base64_Encryption
 *
 * @package   Google\Site_Kit\Tests\Core\Storage
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Tests\Core\Storage;

/**
 * Class Base64_Encryption
 *
 * A dummy encryption implementation for use in testing only.
 *
 * @package Google\Site_Kit\Tests\Core\Storage
 */
class Base64_Encryption {
	/**
	 * Encrypt the given value.
	 *
	 * @param mixed $value
	 *
	 * @return string
	 */
	public function encrypt( $value ) {
		return base64_encode( $value ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
	}

	/**
	 * Decrypt the given value.
	 *
	 * @param mixed $value
	 *
	 * @return bool|string
	 */
	public function decrypt( $value ) {
		return base64_decode( $value ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
	}
}

<?php
/**
 * Base64_Encryption
 *
 * @package   Google\Site_Kit\Tests\Core\Storage
 * @copyright 2019 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Tests\Core\Storage;

/**
 * Class Base64_Encryption
 *
 * A dummy encryption implementation for use in testing only.
 *
 * @package Google\Site_Kit\Tests\Core\Storage
 */
class Base64_Encryption {
	/**
	 * Encrypt the given value.
	 *
	 * @param mixed $value
	 *
	 * @return string
	 */
	public function encrypt( $value ) {
		return base64_encode( $value );
	}

	/**
	 * Decrypt the given value.
	 *
	 * @param mixed $value
	 *
	 * @return bool|string
	 */
	public function decrypt( $value ) {
		return base64_decode( $value );
	}
}

Remove phpcs ignores for base64 encode/decode.


<?php

/**
 * Form for Wave credentials.
 *
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
 */

namespace Wave\Form\Type;

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

use Skyflow\Domain\Users;

class WaveCredentialsType extends AbstractType
{
    /**
     * The skyflow current logged-in user.
     *
     * @var Users
     */
    protected $user;

    /**
     * WaveCredentialsType constructor.
     *
     * @param Users $user The skyflow current logged-in user.
     */
    public function __construct(Users $user)
    {
        $this->user = $user;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('client_id','text')
            ->add('client_secret','text')
            ->add('sandbox', 'checkbox', array('required' => false));
        ;
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $form->setData(array(
            'client_id' => $this->user->getWaveClientId(),
            'client_secret' => $this->user->getWaveClientSecret(),
            'sandbox' => $this->user->getWaveSandbox() ? true : false
        ));
    }

    public function getName()
    {
        return 'app_wave_credentials';
    }
}

<?php

/**
 * Form for Wave credentials.
 *
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
 */

namespace Wave\Form\Type;

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

use Skyflow\Domain\Users;

class WaveCredentialsType extends AbstractType
{
    /**
     * The skyflow current logged-in user.
     *
     * @var Users
     */
    protected $user;

    /**
     * WaveCredentialsType constructor.
     *
     * @param Users $user The skyflow current logged-in user.
     */
    public function __construct(Users $user)
    {
        $this->user = $user;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('client_id', 'text', array('attr' => array('autocomplete' => 'off')))
            ->add('client_secret', 'text', array('attr' => array('autocomplete' => 'off')))
            ->add('sandbox', 'checkbox', array('required' => false));
        ;
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $form->setData(array(
            'client_id' => $this->user->getWaveClientId(),
            'client_secret' => $this->user->getWaveClientSecret(),
            'sandbox' => $this->user->getWaveSandbox() ? true : false
        ));
    }

    public function getName()
    {
        return 'app_wave_credentials';
    }
}

Disable autocomplete for client_id and client_secret inputs on Wave credentials form


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Fix Laravel Schema migrations for Cloud9


<?php

$domains = [
	'development' => ['localhost:3000'],
	'production' => ['production.com.br'],
	'staging' => ['staging.com.br']
];

$currentDomain = str_replace('www.', '', $_SERVER['HTTP_HOST']);

foreach ($domains as $key => $group) {
	foreach ($group as $domain) {
		if(strpos($domain, $currentDomain) !== false) {
			include 'wp-config.' . $key . '.php';
			break;
		}
	}
}

<?php

$domains = [
	'development' => ['localhost'],
	'production' => ['production.com.br'],
	'staging' => ['staging.com.br']
];

$currentDomain = str_replace('www.', '', $_SERVER['HTTP_HOST']);

foreach ($domains as $key => $group) {
	foreach ($group as $domain) {
		if (strpos($currentDomain, $domain) !== false) {
			include 'wp-config-'.$key.'.php';
			break;
		}
	}
}

Fix issue with config files

Fix issue with config files


@if($article->param('show_title'))

    alias) }}">{{ $article->present()->title }}

@endif

    @if($article->param('show_author'))
    Written by: {{ $article->present()->author }}

    @endif

    @if($article->param('show_create_date'))

         Published: {{ $article->present()->datePublished }}

    @endif

    @if($article->param('show_modify_date'))

         Modified: {{ $article->present()->dateModified }}

    @endif

    @if($article->param('show_hits'))

         Hits: {{ $article->present()->hits }}

    @endif

    {!! $article->present()->content !!}

Add own class for each article attribute.


<?php

namespace Tooly\Tests\Script\Helper;

use org\bovigo\vfs\vfsStream;
use phpmock\phpunit\PHPMock;
use Tooly\Script\Helper\Filesystem;

/**
 * @package Tooly\Tests\Script\Helper
 */
class FilesystemTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Filesystem
     */
    private $filesystem;

    /**
     * @var string
     */
    private $testDirectory;

    /**
     * @var string
     */
    private $testFile;

    public function setUp()
    {
        $this->filesystem = new Filesystem;
        $this->testDirectory = sys_get_temp_dir();
        $this->testFile = $this->testDirectory . DIRECTORY_SEPARATOR . 'file';
    }

    public function tearDown()
    {
        if (is_dir($this->testDirectory)) {
            $this->filesystem->removeDirectory($this->testDirectory);
        }
    }

    public function testCanRelativeSymlinkAFile()
    {
        $symlink = $this->testDirectory . DIRECTORY_SEPARATOR . '/foo/symlink';

        $this->assertTrue($this->filesystem->symlinkFile($this->testFile, $symlink));
        $this->assertNotEquals('/', substr(readlink($symlink), '0', 1));
    }
}

<?php

namespace Tooly\Tests\Script\Helper;

use org\bovigo\vfs\vfsStream;
use phpmock\phpunit\PHPMock;
use Tooly\Script\Helper\Filesystem;

/**
 * @package Tooly\Tests\Script\Helper
 */
class FilesystemTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Filesystem
     */
    private $filesystem;

    /**
     * @var string
     */
    private $testDirectory;

    /**
     * @var string
     */
    private $testFile;

    public function setUp()
    {
        $this->filesystem = new Filesystem;
        $this->testDirectory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'test';
        $this->testFile = $this->testDirectory . DIRECTORY_SEPARATOR . 'file';
    }

    public function tearDown()
    {
        if (is_dir($this->testDirectory)) {
            $this->filesystem->removeDirectory($this->testDirectory);
        }
    }

    public function testCanRelativeSymlinkAFile()
    {
        $symlink = $this->testDirectory . DIRECTORY_SEPARATOR . '/foo/symlink';

        $this->assertTrue($this->filesystem->symlinkFile($this->testFile, $symlink));
        $this->assertNotEquals('/', substr(readlink($symlink), '0', 1));
    }
}

Change test directory to get it work on travis ci


<?php
class CaseConverter {
  private $words;

  public function __construct(array $words) {
    if (!validate($words)) throw new TypeError('Passed array contains non-string elements');
    $this->words = $words;
  }

  static private function validateWords(array $words): boolean {
    foreach ($words as $word) {
      if (gettype($word) != 'string') return false;
    }

    return true;
  }

  static public function fromPascalCase(string $text): self {
    $words = array();
    $current = '';

    foreach ($text as $char) {
      $lowcase = strtolower($char);

      if ($lowcase == $char) {
        $current .= $lowcase;
      } else {
        $current or array_push($words, $current);
        $current = $lowcase;
      }
    }

    array_push($words, $current);
    return new self($words);
  }

  static public function fromKebabCase(string $text): self {
    $words = array();
    $current = '';

    foreach ($text as $char) {
      if (($char >= 'A' && $char <= 'Z') || ($char >= 'a' && $char <= 'z')) {
        $current .= strtolower($char);
      } else {
        array_push($words, $current);
      }
    }

    array_push($words, $current);
    return new self($words);
  }

  public function toKebabCase(string $dash = '-'): string {
    return implode($dash, $this->words);
  }
}
?>

Create functions to convert cases

Create functions to convert cases


<?php

use ReflectionClass;

class ClassSize
{

    /**
     * @var ReflectionClass
     */
    private $sus;

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

    /**
     * @throws \Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge
     */
    public function check()
    {
        if ($this->sus->getEndLine() > 300) {
            throw new \Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge($this->sus->getName());
        }
    }
}

<?php
namespace Elfiggo\Brobdingnagian\Detector;

use ReflectionClass;

class ClassSize
{

    /**
     * @var ReflectionClass
     */
    private $sus;

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

    /**
     * @throws \Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge
     */
    public function check()
    {
        if ($this->sus->getEndLine() > 300) {
            throw new \Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge($this->sus->getName());
        }
    }
}

Add namespace back to Class Size

Add namespace back to Class Size


<?php

class Request extends Kohana_Request {

	public static $trusted_proxies = array('127.0.0.1',
											'localhost',
											'localhost.localdomain',
											'104.131.58.157',
											'dev.siggy.borkedlabs.com'
											);
}

<?php

class Request extends Kohana_Request {

	public static $trusted_proxies = array('127.0.0.1',
											'localhost',
											'localhost.localdomain',
											'104.131.58.157',	//proxy 1
											'159.203.193.36',	//proxy 2
											'dev.siggy.borkedlabs.com'
											);
}

Add missing proxy to trusted list

Add missing proxy to trusted list


<?php

/**
 * Abstract controller for actions that provide an API endpoint.
 */
abstract class ApiController extends Controller
{
    /**
     * Given a result payload, format as a JSON response and return
     *
     * @param array $data
     * @return SS_HTTPResponse
     */
    protected function formatResponse(array $data)
    {
        $response = new SS_HTTPResponse();
        $response
            ->addHeader('Content-Type', 'application/json')
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));

        // Don't cache anything in dev mode
        if (Director::get_environment_type() !== 'dev') {
            // Only cache failure messages for one minute, otherwise use the configured cache age
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(__CLASS__, 'cache_age');
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
        }

        return $response;
    }

    /**
     * Overrides this method only to prepend capturing any provided framework version header
     *
     * @inheritDoc
     */
    protected function handleAction($request, $action)
    {
        $frameworkVersionHeader = $request->getHeader('Silverstripe-Framework-Version');

        if ($frameworkVersionHeader) {
            ApiCallerVersions::create([
                'Endpoint' => $request->getURL(),
                'Version' => $frameworkVersionHeader,
            ])->write();
        }

        return parent::handleAction($request, $action);
    }
}

<?php

/**
 * Abstract controller for actions that provide an API endpoint.
 */
abstract class ApiController extends Controller
{
    /**
     * Given a result payload, format as a JSON response and return
     *
     * @param array $data
     * @return SS_HTTPResponse
     */
    protected function formatResponse(array $data)
    {
        $response = new SS_HTTPResponse();
        $response
            ->addHeader('Content-Type', 'application/json')
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));

        // Don't cache anything in dev mode
        if (Director::get_environment_type() !== 'dev') {
            // Only cache failure messages for one minute, otherwise use the configured cache age
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(static::class, 'cache_age');
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
        }

        return $response;
    }

    /**
     * Overrides this method only to prepend capturing any provided framework version header
     *
     * @inheritDoc
     */
    protected function handleAction($request, $action)
    {
        $frameworkVersionHeader = $request->getHeader('Silverstripe-Framework-Version');

        if ($frameworkVersionHeader) {
            ApiCallerVersions::create([
                'Endpoint' => $request->getURL(),
                'Version' => $frameworkVersionHeader,
            ])->write();
        }

        return parent::handleAction($request, $action);
    }
}

FIX Late static binding in config property for max age


<?php
date_default_timezone_set('Europe/Amsterdam');
define('APPLICATION_ENV', 'testing');
$rootPath = dirname(__FILE__).'/..';

require_once $rootPath.'/application/init.php';

$application = new Garp_Application(
	APPLICATION_ENV,
	APPLICATION_PATH.'/configs/application.ini'
);

$application->bootstrap();
Zend_Registry::set('application', $application);

error_reporting(-1);
ini_set('display_errors', 'stdout');
ini_set('display_startup_errors', true);

<?php
date_default_timezone_set('Europe/Amsterdam');
define('APPLICATION_ENV', 'testing');
$rootPath = dirname(__FILE__).'/..';

require_once $rootPath.'/application/init.php';

$application = new Garp_Application(
	APPLICATION_ENV,
	APPLICATION_PATH.'/configs/application.ini'
);

$application->bootstrap();
Zend_Registry::set('application', $application);

$mem = new Garp_Util_Memory();
$mem->useHighMemory();

error_reporting(-1);
ini_set('display_errors', 'stdout');
ini_set('display_startup_errors', true);

Use high memory when executing unit tests


<?php
require_once("/var/www/secure_settings/class.FlipsideSettings.php");
require_once('Autoload.php');
class DataSetFactory
{
    static function get_data_set($set_name)
    {
        static $instances = array();
        if(isset($instances[$set_name]))
        {
            return $instances[$set_name];
        }
        if(!isset(FlipsideSettings::$dataset[$set_name]))
        {
            throw new Exception('Unknown dataset name '.$set_name);
        }
        $set_data = FlipsideSettings::$dataset[$set_name];
        $class_name = '\\Data\\'.$set_data['type'];
        $obj = new $class_name($set_data['params']);
        $instances[$set_name] = $obj;
        return $obj;
    }
}
?>

<?php
require_once("/var/www/secure_settings/class.FlipsideSettings.php");
require_once('Autoload.php');
class DataSetFactory
{
    static function get_data_set($set_name)
    {
        static $instances = array();
        if(isset($instances[$set_name]))
        {
            return $instances[$set_name];
        }
        if(!isset(FlipsideSettings::$dataset) || !isset(FlipsideSettings::$dataset[$set_name]))
        {
            throw new Exception('Unknown dataset name '.$set_name);
        }
        $set_data = FlipsideSettings::$dataset[$set_name];
        $class_name = '\\Data\\'.$set_data['type'];
        $obj = new $class_name($set_data['params']);
        $instances[$set_name] = $obj;
        return $obj;
    }
}
?>

Stop errors if no datasets are defined

Stop errors if no datasets are defined


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

use Symfony\Component\Console\Application;

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

date_default_timezone_set('Europe/Madrid');

$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
    __DIR__ . '/src/SoftwarePackages',
    'Ontic\Yaes\SoftwarePackages'
);

putenv("LC_ALL=" . getenv('LANG'));
bindtextdomain("messages", "locale");
textdomain("messages");

$application = new Application();
foreach($softwarePackages as $package)
{
    $application->addCommands($package->getCommands());
}

$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();

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

use Symfony\Component\Console\Application;

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

date_default_timezone_set('Europe/Madrid');

$loader = new \Ontic\Yaes\Loaders\SoftwarePackagesLoader();
$softwarePackages = $loader->findSoftwarePackages(
    __DIR__ . '/src/SoftwarePackages',
    'Ontic\Yaes\SoftwarePackages'
);

setlocale(LC_ALL, getenv('LANG'));
bindtextdomain("messages", "locale");
textdomain("messages");

$application = new Application();
foreach($softwarePackages as $package)
{
    $application->addCommands($package->getCommands());
}

$application->add(new \Ontic\Yaes\Command\IdentifyCommand($softwarePackages));
$application->add(new \Ontic\Yaes\Command\ScanCommand($softwarePackages));
$application->run();

Fix CLI i18n (for real)

Fix CLI i18n (for real)


<?php
	# Member template for the 'medlem' shortcode function

	# The $meta includes member info
	# Uses a $content variable if available, otherwise the meta description of the actual member.

	$year = $meta['it_year'];
	$description = ($content != null) ? $content : $meta['description'];
	$avatar_size = ($args != null) ? $args['avatar_size'] : 96;
?>

		<?php echo get_avatar($id, $avatar_size); ?>

		<?php if($role) : ?>
		<hgroup>

<?php user_fullname(get_userdata($id));?>

<?php echo $role;?>

		</hgroup>
		<?php else : ?>

<?php user_fullname(get_userdata($id));?>

		<?php endif;?>

			<?php echo strip_tags($description);?>

<?php
	# Member template for the 'medlem' shortcode function

	# The $meta includes member info
	# Uses a $content variable if available, otherwise the meta description of the actual member.

	$year = $meta['it_year'];
	$userdata = get_userdata($id);
	$description = ($content != null) ? $content : $meta['description'];
	$avatar_size = ($args != null) ? $args['avatar_size'] : 96;
	# Shown email may be overriden in the shortcode attribute 'contact'
	$user_contact = ($contact != null) ? $contact : $userdata->data->user_email;
?>

		<?php echo get_avatar($id, $avatar_size); ?>

		<?php if($role) : ?>
		<hgroup>

<?php user_fullname($userdata);?>

<?php echo $role;?>

		</hgroup>
		<?php else : ?>

<?php user_fullname($userdata);?>

		<?php endif;?>

			<?php echo strip_tags($description);?>

			<?php if($user_contact) : ?>
			Kontakt: <a href="mailto:<?php echo $user_contact;?>"><?php echo $user_contact;?>
			<?php endif;?>

Add attribute for 'contact' in person shortcode


<?php
namespace ZBateson\MailMimeParser\Header\Part;

use PHPUnit_Framework_TestCase;
use DateTime;

/**
 * Description of DateTest
 *
 * @group HeaderParts
 * @group DatePart
 * @covers ZBateson\MailMimeParser\Header\Part\DatePart
 * @author Zaahid Bateson
 */
class DatePartTest extends PHPUnit_Framework_TestCase
{
    public function testDateString()
    {
        $value = 'Wed, 17 May 2000 19:08:29 -0400';
        $part = new DatePart($value);
        $this->assertEquals($value, $part->getValue());
        $date = $part->getDateTime();
        $this->assertNotEmpty($date);
        $this->assertEquals($value, $date->format(DateTime::RFC2822));
    }
}

<?php
namespace ZBateson\MailMimeParser\Header\Part;

use PHPUnit_Framework_TestCase;
use DateTime;

/**
 * Description of DateTest
 *
 * @group HeaderParts
 * @group DatePart
 * @covers ZBateson\MailMimeParser\Header\Part\DatePart
 * @author Zaahid Bateson
 */
class DatePartTest extends PHPUnit_Framework_TestCase
{
    public function testDateString()
    {
        $value = 'Wed, 17 May 2000 19:08:29 -0400';
        $part = new DatePart($value);
        $this->assertEquals($value, $part->getValue());
        $date = $part->getDateTime();
        $this->assertNotEmpty($date);
        $this->assertEquals($value, $date->format(DateTime::RFC2822));
    }

    public function testInvalidDate()
    {
        $value = 'Invalid Date';
        $part = new DatePart($value);
        $this->assertEquals($value, $part->getValue());
        $date = $part->getDateTime();
        $this->assertNull($date);
    }
}

Add DatePart invalid date unit test

Add DatePart invalid date unit test


<?php namespace Modules\Menu\Database\Models;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model {

	public $table = 'menu';

	public $timestamps = false;

    protected $fillable = ["text","link","position","parent_id","depth","left","right","public"];

}

<?php namespace Modules\Menu\Database\Models;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model {

	public $table = 'menu';

	public $timestamps = false;

	protected $fillable = ["text","link","position","parent_id","depth","left","right","public"];

	public function children()
	{
		return $this->whereParentId($this->id)->orderBy('position')->get();
	}

	public static function hierarchy($parent_id = 0)
	{
		$items = self::whereParent_id($parent_id)->orderBy('position')->get();

		foreach($items as $item)
		{
			$item->items = self::hierarchy($item->id);
		}

		return $items;
	}

}

Add usefull methods for working with childrens of menu


<?
/**
*
* A wrapper class for results from the search engine, allowing for abstraction in case search engines are changed in the future.
* @package Utilities
* @subpackage Search
*/
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedPageList extends PageList {

	protected $indexModeSimple = false;

	public function setSimpleIndexMode($indexModeSimple) {
		$this->indexModeSimple = $indexModeSimple;
	}

	public function getPage() {
		if ($this->indexModeSimple) {
			$this->sortBy('cDatePublic', 'desc');
		} else {
			$this->sortByMultiple('cIndexScore desc', 'cDatePublic desc');
		}
		$r = parent::getPage();
		$results = array();
		foreach($r as $c) {
			$results[] = array('cID' => $c->getCollectionID(), 'cName' => $c->getCollectionName(), 'cDescription' => $c->getCollectionDescription(), 'score' => $c->getPageIndexScore(), 'cPath' => $c->getCollectionPath(), 'content' => $c->getPageIndexContent());
		}
		return $results;
	}
}

<?
/**
*
* A wrapper class for results from the search engine, allowing for abstraction in case search engines are changed in the future.
* @package Utilities
* @subpackage Search
*/
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedPageList extends PageList {

	protected $indexModeSimple = false;

	public function setSimpleIndexMode($indexModeSimple) {
		$this->indexModeSimple = $indexModeSimple;
	}

	public function getPage() {
		if ($this->indexModeSimple) {
			$this->sortBy('cDatePublic', 'desc');
		} else {
			$this->sortByMultiple('cIndexScore desc', 'cDatePublic desc');
		}
		$r = parent::getPage();
		$results = array();
		foreach($r as $c) {
			$results[] = array('cID' => $c->getCollectionID(), 'cName' => $c->getCollectionName(), 'cDescription' => $c->getCollectionDescription(), 'score' => $c->getPageIndexScore(), 'cPath' => $c->getCollectionPath(), 'content' => $c->getPageIndexContent(), 'cDatePublic' => $c->getCollectionDatePublic());
		}
		return $results;
	}
}

Add cDatePublic to indexed page list

Add cDatePublic to indexed page list


<?php namespace Modules\Page\Database\Seeders;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\Page\Repositories\PageRepository;

class PageDatabaseSeeder extends Seeder
{
    /**
     * @var PageRepository
     */
    private $page;

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

    public function run()
    {
        Model::unguard();

        $data = [
            'template' => 'home',
            'is_home' => 1,
            'en' => [
                'title' => 'Home page',
                'slug' => 'home',
                'body' => '
You made it!

You've installed AsgardCMS and are ready to proceed to the administration area.

What's next ?

Learn how you can develop modules for AsgardCMS by reading our documentation.

',
                'meta_title' => 'Home page',
            ],
            'fr' => [
                'title' => 'Page d\'accueil',
                'slug' => 'accueil',
                'body' => '
You made it!

You've installed AsgardCMS and are ready to proceed to the administration area.

What's next ?

Learn how you can develop modules for AsgardCMS by reading our documentation.

',
                'meta_title' => 'Page d\'accueil',
            ],
        ];
        $this->page->create($data);
    }
}

<?php namespace Modules\Page\Database\Seeders;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Modules\Page\Repositories\PageRepository;

class PageDatabaseSeeder extends Seeder
{
    /**
     * @var PageRepository
     */
    private $page;

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

    public function run()
    {
        Model::unguard();

        $data = [
            'template' => 'home',
            'is_home' => 1,
            'en' => [
                'title' => 'Home page',
                'slug' => 'home',
                'body' => '
You made it!

You've installed AsgardCMS and are ready to proceed to the administration area.

What's next ?

Learn how you can develop modules for AsgardCMS by reading our documentation.

',
                'meta_title' => 'Home page',
            ],
        ];
        $this->page->create($data);
    }
}

Remove the french default page

Remove the french default page


<?php
namespace Neos\Flow\Http;

/**
 * A Flow specific uploaded file.
 */
class FlowUploadedFile extends UploadedFile
{
    /**
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     *
     * @var array|string
     */
    protected $originallySubmittedResource;

    /**
     * @var string
     */
    protected $collectionName;

    /**
     * @return array|string
     */
    public function getOriginallySubmittedResource()
    {
        return $this->originallySubmittedResource;
    }

    /**
     * Sets a previously submitted resource reference.
     *
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @param array|string $originallySubmittedResource
     */
    public function setOriginallySubmittedResource($originallySubmittedResource)
    {
        $this->originallySubmittedResource = $originallySubmittedResource;
    }

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

    /**
     * @param string $collectionName
     */
    public function setCollectionName($collectionName)
    {
        $this->collectionName = $collectionName;
    }
}

<?php
namespace Neos\Flow\Http;

/**
 * A Flow specific uploaded file.
 */
class FlowUploadedFile extends UploadedFile
{
    /**
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @var array|string
     */
    protected $originallySubmittedResource;

    /**
     * @var string
     */
    protected $collectionName;

    /**
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @return array|string
     */
    public function getOriginallySubmittedResource()
    {
        return $this->originallySubmittedResource;
    }

    /**
     * Sets a previously submitted resource reference.
     *
     * This is either the persistent identifier of a previously submitted resource file
     * or an array with the "__identity" key set to the persistent identifier.
     *
     * @param array|string $originallySubmittedResource
     */
    public function setOriginallySubmittedResource($originallySubmittedResource)
    {
        $this->originallySubmittedResource = $originallySubmittedResource;
    }

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

    /**
     * @param string $collectionName
     */
    public function setCollectionName($collectionName)
    {
        $this->collectionName = $collectionName;
    }
}

Add a missing method description

TASK: Add a missing method description


<?php

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $this->view->message = 'Application error';
                break;
        }

        // Log exception, if logger available
        if ($log = $this->getLog()) {
            $log->crit($this->view->message, $errors->exception);
        }

        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }

        $this->view->request   = $errors->request;
    }

    public function getLog()
    {
        $bootstrap = $this->getInvokeArg('bootstrap');
        if (!$bootstrap->hasPluginResource('Log')) {
            return false;
        }
        $log = $bootstrap->getResource('Log');
        return $log;
    }
}

<?php

class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $this->view->message = 'Application error';
                break;
        }

        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }

        $this->view->request   = $errors->request;
    }
}

Remove logging code from Error Controller.


<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;

class ByDbxrefId
{
    private $manager;

    /**
     * ByDbxrefId constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $this->db = $this->getManagerFromQuery($query)->getConnection();
        if(!$query->has('ids') || !is_array($query->get('ids')) || count($query->get('ids')) === 0 || !$query->has('db')){
            return array();
        }
        $ids = $query->get('ids');
        $result = array_fill_keys($ids, null);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $query_get_mapping = <<<EOF
SELECT fennec_id, identifier
    FROM fennec_dbxref
        WHERE db_id=(SELECT db_id FROM db WHERE name=?)
        AND identifier IN ({$placeholders})
EOF;
        $stm_get_mapping = $this->db->prepare($query_get_mapping);
        $stm_get_mapping->execute(array_merge([$query->get('db')], $ids));

        while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){
            $id = $row['identifier'];
            if($result[$id] === null){
                $result[$id] = $row['fennec_id'];
            } else {
                if(! is_array($result[$id]) ){
                    $result[$id] = [$result[$id]];
                }
                $result[$id][] = $row['fennec_id'];
            }
        }

        return $result;
    }
}

<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;

class ByDbxrefId
{
    private $manager;

    /**
     * ByDbxrefId constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @inheritdoc
     */
    public function execute($ids, $dbname)
    {
        return $this->manager->getRepository('AppBundle:FennecDbxref')->getIds($ids, $dbname);
    }
}

Update service for mapping ids bydbxref

Update service for mapping ids bydbxref


<?php

class TestimonialsExtension extends SiteTreeExtension
{

    private static $has_many = [
        'Testimonials' => 'Testimonial'
    ];

    public function updateCMSFields(FieldList $fields)
    {

        /** @var GridFieldConfig $gridConfig */
        $gridConfig = GridFieldConfig::create();

        $gridConfig
            ->addComponent(new GridFieldButtonRow('before'))
            ->addComponent(new GridFieldAddNewButton('buttons-before-left'))
            ->addComponent(new GridFieldToolbarHeader())
            ->addComponent(new  GridFieldSortableHeader())
            ->addComponent(new GridFieldOrderableRows('SortOrder'))
            ->addComponent($dataColumns = new GridFieldDataColumns())
            ->addComponent(new GridFieldEditButton())
            ->addComponent(new GridFieldDeleteAction())
            ->addComponent(new GridFieldDetailForm());

        $dataColumns->setDisplayFields([
            'Title' => 'Author',
            'Testimonial.Summary' => 'Testimonial Preview',
        ]);

        /** @var TabSet $rootTab */
        //We need to repush Metadata to ensure it is the last tab
        $rootTab = $fields->fieldByName('Root');
        $fields->removeByName('Testimonials');
        $rootTab->push(Tab::create('Testimonials'));

        $GridField = GridField::create('Testimonials', 'Testimonials', $this->owner->Testimonials(), $gridConfig);

        $fields->addFieldToTab('Root.Testimonials', $GridField);

        return $fields;
    }
}

<?php

class TestimonialsExtension extends SiteTreeExtension
{

    private static $has_many = [
        'Testimonials' => 'Testimonial'
    ];

    public function updateCMSFields(FieldList $fields)
    {

        /** @var GridFieldConfig $gridConfig */
        $gridConfig = GridFieldConfig::create();

        $gridConfig
            ->addComponent(new GridFieldButtonRow('before'))
            ->addComponent(new GridFieldAddNewButton('buttons-before-left'))
            ->addComponent(new GridFieldToolbarHeader())
            ->addComponent(new  GridFieldSortableHeader())
            ->addComponent(new GridFieldOrderableRows('SortOrder'))
            ->addComponent($dataColumns = new GridFieldDataColumns())
            ->addComponent(new GridFieldEditButton())
            ->addComponent(new GridFieldDeleteAction())
            ->addComponent(new GridFieldDetailForm());

        $dataColumns->setDisplayFields([
            'Title' => 'Author',
            'Testimonial.Summary' => 'Testimonial Preview',
        ]);

        /** @var TabSet $rootTab */
        //We need to repush Metadata to ensure it is the last tab
        $rootTab = $fields->fieldByName('Root');
        $fields->removeByName('Testimonials');

        if ($this->owner->exists()) {
            $rootTab->push(Tab::create('Testimonials'));
            $GridField = GridField::create('Testimonials', 'Testimonials', $this->owner->Testimonials(), $gridConfig);
            $fields->addFieldToTab('Root.Testimonials', $GridField);
        }

        return $fields;
    }
}

Fix to work with DataObjects

Fix to work with DataObjects


<?php
/**
 * This file is part of the Napp\AeroGearPush package.
 *
 * (c) NAPP <http://napp.dk>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Napp\AeroGearPush\Request;

/**
 * Class createApplicationRequest
 *
 * @package Napp\AeroGearPush\Request
 * @author  Hasse Ramlev Hansen <hasse@ramlev.dk>
 */
class createApplicationRequest extends abstractApplicationRequest
{
    /**
     * createApplicationRequest constructor.
     */
    public function __construct()
    {
        $this->setEndpoint('applications');
        $this->setMethod('POST');
    }
}

<?php
/**
 * This file is part of the Napp\AeroGearPush package.
 *
 * (c) NAPP <http://napp.dk>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Napp\AeroGearPush\Request;

/**
 * Class createApplicationRequest
 *
 * @package Napp\AeroGearPush\Request
 * @author  Hasse Ramlev Hansen <hasse@ramlev.dk>
 */
class CreateApplicationRequest extends abstractApplicationRequest
{
    /**
     * createApplicationRequest constructor.
     */
    public function __construct()
    {
        $this->setEndpoint('applications');
        $this->setMethod('POST');
    }
}

Fix classname to correct camelcase

Fix classname to correct camelcase


<?php

namespace Stamp\Action;

class ParseVariableAction extends BaseAction implements ActionInterface
{
    private $text = '';
    private $regex = '';

    public function getActionName()
    {
        return 'parse_variable';
    }

    public function setParams($array)
    {
        $this->setText($array['text']);
        $this->setRegex($array['regex']);
    }

    public function setText($text)
    {
        $this->text = $text;
    }

    public function setRegex($regex)
    {
        $this->regex = $regex;
    }

    public function exec()
    {
        try {
            $resultOfMatching = preg_match($this->regex, $this->text, $matches);
        } catch (\PhpSpec\Exception\Example\ErrorException $e) {
            throw new \RuntimeException(sprintf('Error during parsing regex [[%s]]', $this->regex));
        }

        if ($resultOfMatching) {

            unset($matches[0]);
            unset($matches[1]);

            if ($this->verbose) {
                $key = array_keys($matches)[0];
                $this->setOutput(sprintf('parse_variable["%s"=>"%s"]', $key, $matches[$key]));
            }

            $this->setResult($matches);

            return true;
        }
        return false;
    }

}

<?php

namespace Stamp\Action;

use RuntimeException;

class ParseVariableAction extends BaseAction implements ActionInterface
{
    private $text = '';
    private $regex = '';

    public function getActionName()
    {
        return 'parse_variable';
    }

    public function setParams($array)
    {
        $this->setText($array['text']);
        $this->setRegex($array['regex']);
    }

    public function setText($text)
    {
        $this->text = $text;
    }

    public function setRegex($regex)
    {
        $this->regex = $regex;
    }

    public function exec()
    {
        try {
            $resultOfMatching = preg_match($this->regex, $this->text, $matches);
        } catch (\Exception $e) {
            throw new RuntimeException(sprintf('Error during parsing regex [[%s]]', $this->regex));
        }

        if ($resultOfMatching) {

            unset($matches[0]);
            unset($matches[1]);

            if ($this->verbose) {
                $key = array_keys($matches)[0];
                $this->setOutput(sprintf('parse_variable["%s"=>"%s"]', $key, $matches[$key]));
            }

            $this->setResult($matches);

            return true;
        }
        return false;
    }

}

Use \Exception when in try-catch for pcre exceptions


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class RecruitingCampaignRecipient extends Model
{
    use SoftDeletes;

    /**
     * Get the user that owns the phone.
     */
    public function recruitingCampaign()
    {
        return $this->belongsTo('App\RecruitingCampaign');
    }

    /**
     * Get the user that owns the phone.
     */
    public function recruitingVisit()
    {
        return $this->belongsTo('App\RecruitingVisit');
    }

    /**
     * Get the user that is related to the model.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class RecruitingCampaignRecipient extends Model
{
    use SoftDeletes;
    use Notifiable;

    /**
     * Get the user that owns the phone.
     */
    public function recruitingCampaign()
    {
        return $this->belongsTo('App\RecruitingCampaign');
    }

    /**
     * Get the user that owns the phone.
     */
    public function recruitingVisit()
    {
        return $this->belongsTo('App\RecruitingVisit');
    }

    /**
     * Get the user that is related to the model.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * Route notifications for the mail channel.
     *
     * @return string
     */
    public function routeNotificationForMail()
    {
        return $this->email_address;
    }
}

Make this a functional notifiable class

Make this a functional notifiable class


<?php
return [

    /**
     * The storage config
     */
    "storage" => [
        /**
         * Returns the folder name of the chunks. The location is in storage/app/{folder_name}
         */
        "chunks" => "chunks",
        "disk" => "local"
    ],
    "clear" => [
        /**
         * How old chunks we should delete
         */
        "timestamp" => "-3 HOURS",
        "schedule" => [
            "enabled" => true,
            "cron" => "0 */1 * * * *" // run every hour
        ]
    ],
    "chunk" => [
        // setup for the chunk naming setup to ensure same name upload at same time
        "name" => [
            "use" => [
                "session" => true, // should the chunk name use the session id? The uploader must send cookie!,
                "browser" => false // instead of session we can use the ip and browser?
            ]
        ]
    ]
];

<?php
return [

    /**
     * The storage config
     */
    "storage" => [
        /**
         * Returns the folder name of the chunks. The location is in storage/app/{folder_name}
         */
        "chunks" => "chunks",
        "disk" => "local"
    ],
    "clear" => [
        /**
         * How old chunks we should delete
         */
        "timestamp" => "-3 HOURS",
        "schedule" => [
            "enabled" => true,
            "cron" => "25 * * * *" // run every hour on the 25th minute
        ]
    ],
    "chunk" => [
        // setup for the chunk naming setup to ensure same name upload at same time
        "name" => [
            "use" => [
                "session" => true, // should the chunk name use the session id? The uploader must send cookie!,
                "browser" => false // instead of session we can use the ip and browser?
            ]
        ]
    ]
];

Set scheduler to run every hour on the 25th minute

Fixes ‘InvalidArgumentException  : 5 is not a valid position’ when doing ‘artisan schedule:run’


<?php
/**
 * @author Patsura Dmitry @ovr <talk@dmtry.me>
 */

namespace RestApp\Common\Controller;

use Exception;
use ReflectionExtension;

/**
 * Class IndexController
 * @Path("/api")
 */
class IndexController extends \Owl\Mvc\Controller
{
    /**
     * @Get
     * @Url("/", name="default")
     */
    public function indexAction()
    {
        /** @var \Owl\Mvc\View $view */
        $view = $this->di->get('view');
        return $view->render('index/index.phtml', null);
    }

    /**
     * @Get
     * @Url("/ping", name="api-ping")
     */
    public function pingAction()
    {
        return ['pong'];
    }

    /**
     * @Get
     * @Url("/version", name="api-show-version")
     */
    public function versionAction()
    {
        $ext = new ReflectionExtension('owl');

        return [
            'version' => '0.1-dev',
            'owl' => $ext->getVersion()
        ];
    }

    public function errorAction()
    {
        return array(
            'message' => 'Not found',
            'uri' => $this->request->getUri()
        );
    }

    public function exceptionAction(Exception $e)
    {
        if ($e->getCode() >= 400) {
            $this->response->setCode($e->getCode());
        }

        return array(
            $e->getMessage()
        );
    }
}

<?php
/**
 * @author Patsura Dmitry @ovr <talk@dmtry.me>
 */

namespace RestApp\Common\Controller;

use Exception;
use ReflectionExtension;

/**
 * Class IndexController
 * @Path("/api")
 */
class IndexController extends \Owl\Mvc\Controller
{
    /**
     * @Get
     * @Url("/", name="default")
     */
    public function indexAction()
    {
        /** @var \Owl\Mvc\View $view */
        $view = $this->di->get('view');
        return $view->render('index/index.phtml', null);
    }

    /**
     * @Get
     * @Url("/ping", name="api-ping")
     */
    public function pingAction()
    {
        return ['pong'];
    }

    /**
     * @Get
     * @Url("/version", name="api-show-version")
     */
    public function versionAction()
    {
        $ext = new ReflectionExtension('owl');

        return [
            'version' => '0.1-dev',
            'owl' => $ext->getVersion()
        ];
    }

    public function errorAction()
    {
        return array(
            'message' => 'Not found',
            'uri' => $this->request->getUri()
        );
    }

    public function exceptionAction(Exception $e)
    {
        if ($e->getCode() >= 400) {
            $this->response->setStatusCode($e->getCode());
        }

        return array(
            $e->getMessage()
        );
    }
}

Fix BC with setCode -> setStatusCode

Fix BC with setCode -> setStatusCode


<?php

class Papi_Lib_Core_Deprecated_Test extends WP_UnitTestCase {

	public function setUp() {
		parent::setUp();
		$_GET = [];

		add_action( 'deprecated_function_run', [$this, 'deprecated_function_run'] );
		tests_add_filter( 'papi/settings/directories', function () {
			return [1,  PAPI_FIXTURE_DIR . '/page-types'];
		} );

		$this->post_id = $this->factory->post->create();
		update_post_meta( $this->post_id, PAPI_PAGE_TYPE_KEY, 'simple-page-type' );
	}

	public function deprecated_function_run( $function ) {
		add_filter( 'deprecated_function_trigger_error', '__return_false' );
	}

	public function tearDown() {
		parent::tearDown();
		remove_filter( 'deprecated_function_trigger_error', '__return_false' );
		unset( $_GET, $this->post_id );
	}
}

<?php

class Papi_Lib_Core_Deprecated_Test extends WP_UnitTestCase {

	public function setUp() {
		parent::setUp();
		$_GET = [];

		add_action( 'deprecated_function_run', [$this, 'deprecated_function_run'] );
		tests_add_filter( 'papi/settings/directories', function () {
			return [1,  PAPI_FIXTURE_DIR . '/page-types'];
		} );

		$this->post_id = $this->factory->post->create();
		update_post_meta( $this->post_id, PAPI_PAGE_TYPE_KEY, 'simple-page-type' );
	}

	public function deprecated_function_run( $function ) {
		add_filter( 'deprecated_function_trigger_error', '__return_false' );
	}

	public function tearDown() {
		parent::tearDown();
		remove_filter( 'deprecated_function_trigger_error', '__return_false' );
		unset( $_GET, $this->post_id );
	}

	public function test_deprecated() {
		$this->assertTrue( true );
	}
}

Add simple test to deprecated test class


<?php

use Laravel\Passport\Passport;
use PHPUnit\Framework\TestCase;

class PassportTest extends TestCase
{
    public function test_scopes_can_be_managed()
    {
        Passport::tokensCan([
            'user' => 'get user information',
        ]);

        $this->assertTrue(Passport::hasScope('user'));
        $this->assertEquals(['user'], Passport::scopeIds());
        $this->assertEquals('user', Passport::scopes()[0]->id);
    }
}

<?php

use Laravel\Passport\AuthCode;
use Laravel\Passport\Client;
use Laravel\Passport\Passport;
use Laravel\Passport\PersonalAccessClient;
use Laravel\Passport\Token;
use PHPUnit\Framework\TestCase;

class PassportTest extends TestCase
{
    public function test_scopes_can_be_managed()
    {
        Passport::tokensCan([
            'user' => 'get user information',
        ]);

        $this->assertTrue(Passport::hasScope('user'));
        $this->assertEquals(['user'], Passport::scopeIds());
        $this->assertEquals('user', Passport::scopes()[0]->id);
    }

    public function test_auth_code_instance_can_be_created()
    {
        $authCode = Passport::authCode();

        $this->assertInstanceOf(AuthCode::class, $authCode);
        $this->assertInstanceOf(Passport::authCodeModel(), $authCode);
    }

    public function test_client_instance_can_be_created()
    {
        $client = Passport::client();

        $this->assertInstanceOf(Client::class, $client);
        $this->assertInstanceOf(Passport::clientModel(), $client);
    }

    public function test_personal_access_client_instance_can_be_created()
    {
        $client = Passport::personalAccessClient();

        $this->assertInstanceOf(PersonalAccessClient::class, $client);
        $this->assertInstanceOf(Passport::personalAccessClientModel(), $client);
    }

    public function test_token_instance_can_be_created()
    {
        $token = Passport::token();

        $this->assertInstanceOf(Token::class, $token);
        $this->assertInstanceOf(Passport::tokenModel(), $token);
    }
}

Make sure added methods are tested

Make sure added methods are tested


<?php

function debug_collectionInfoStart($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data\n", $log);
    }
}

function debug_collectionInfoEnd($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Finished collecting data\n\n", $log);
    }
}

function debug_collectionInterval($debug, $interval, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
        echo $echo;
    }

    if ($log == TRUE) {
    	if (!file_exists("logs/debug.log")) {
    		mkdir("logs");
    		$dbglog = fopen("logs/debug.log", "w");
			fclose($dbglog);
    	}

        file_put_contents("logs/debug.log", date("r") . "  -  " . $echo, FILE_APPEND);
    }
}
?>

<?php

function debug_collectionInfoStart($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data\n", $log);
    }
}

function debug_collectionInfoEnd($debug, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Finished collecting data\n\n", $log);
    }
}

function debug_collectionInterval($debug, $interval, $log) {
    if ($debug == TRUE) {
        debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log);
    }
}

function debug($echo, $log) {

    if ($echo != "" && $echo !== NULL) {
        echo $echo;
    }

    if ($log == TRUE) {
    	if (!file_exists("logs/debug.log")) {
    		$dbglog = fopen("logs/debug.log", "w");
			fclose($dbglog);
    	}

        file_put_contents("logs/debug.log", date("r") . "  -  " . $echo, FILE_APPEND);
    }
}
?>

Revert "Make logs dir if missing"

Revert "Make logs dir if missing"

This reverts commit ad9191f5c4cb65994aebcab2953f79c885c35248.


<?php

namespace Clue\PharComposer\Command;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Clue\PharComposer\PharComposer;

class Build extends Command
{
    protected function configure()
    {
        $this->setName('build')
             ->setDescription('Build phar for the given composer project')
             ->addArgument('path', InputArgument::OPTIONAL, 'Path to project directory or composer.json', '.')
           /*->addOption('dev', null, InputOption::VALUE_NONE, 'If set, Whether require-dev dependencies should be shown') */;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $input->getArgument('path');

        $pharcomposer = new PharComposer($path);
        $pharcomposer->build();
    }
}

<?php

namespace Clue\PharComposer\Command;

use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Clue\PharComposer\PharComposer;
use InvalidArgumentException;

class Build extends Command
{
    protected function configure()
    {
        $this->setName('build')
             ->setDescription('Build phar for the given composer project')
             ->addArgument('path', InputArgument::OPTIONAL, 'Path to project directory or composer.json', '.')
           /*->addOption('dev', null, InputOption::VALUE_NONE, 'If set, Whether require-dev dependencies should be shown') */;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $input->getArgument('path');
        if (is_dir($path)) {
            $path = rtrim($path, '/') . '/composer.json';
        }
        if (!is_file($path)) {
            throw new InvalidArgumentException('The given path "' . $path . '" is not a readable file');
        }

        $pharcomposer = new PharComposer($path);
        $pharcomposer->build();
    }
}

Validate input file and support giving in a project directory


<?php

final class PhabricatorUIExamplesApplication extends PhabricatorApplication {

  public function getBaseURI() {
    return '/uiexample/';
  }

  public function getShortDescription() {
    return pht('Developer UI Examples');
  }

  public function getName() {
    return pht('UIExamples');
  }

  public function getFontIcon() {
    return 'fa-magnet';
  }

  public function getTitleGlyph() {
    return "\xE2\x8F\x9A";
  }

  public function getFlavorText() {
    return pht('A gallery of modern art.');
  }

  public function getApplicationGroup() {
    return self::GROUP_DEVELOPER;
  }

  public function getApplicationOrder() {
    return 0.110;
  }

  public function getRoutes() {
    return array(
      '/uiexample/' => array(
        '' => 'PhabricatorUIExampleRenderController',
        'view/(?P<class>[^/]+)/' => 'PhabricatorUIExampleRenderController',
      ),
    );
  }

}

<?php

final class PhabricatorUIExamplesApplication extends PhabricatorApplication {

  public function getBaseURI() {
    return '/uiexample/';
  }

  public function getShortDescription() {
    return pht('Developer UI Examples');
  }

  public function getName() {
    return pht('UIExamples');
  }

  public function getFontIcon() {
    return 'fa-magnet';
  }

  public function getTitleGlyph() {
    return "\xE2\x8F\x9A";
  }

  public function getFlavorText() {
    return pht('A gallery of modern art.');
  }

  public function getApplicationGroup() {
    return self::GROUP_DEVELOPER;
  }

  public function isPrototype() {
    return true;
  }

  public function getApplicationOrder() {
    return 0.110;
  }

  public function getRoutes() {
    return array(
      '/uiexample/' => array(
        '' => 'PhabricatorUIExampleRenderController',
        'view/(?P<class>[^/]+)/' => 'PhabricatorUIExampleRenderController',
      ),
    );
  }

}

Mark UIExamples as a prototype

Mark UIExamples as a prototype

Summary: Ref T9103. This application is only useful for developing Phabricator, and in general is not kept "production ready". Mark it as a prototype.

Test Plan: visit /applications/, see it marked as prototype.

Reviewers: epriestley

Reviewed By: epriestley

Subscribers: Korvin

Maniphest Tasks: T9103

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


<?php
/**
 * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
 *
 * @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/>.
 *
 */
script('core', 'login/redirect');
style('core', 'login/authpicker');

/** @var array $_ */
/** @var \OCP\IURLGenerator $urlGenerator */
$urlGenerator = $_['urlGenerator'];
?>

<?php p($l->t('Redirecting …')) ?>

<form method="POST" action="<?php p($urlGenerator->linkToRouteAbsolute('core.ClientFlowLogin.generateAppPassword')) ?>">
	<input type="hidden" name="clientIdentifier" value="<?php p($_['clientIdentifier']) ?>" />
	<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" />
	<input type="hidden" name="stateToken" value="<?php p($_['stateToken']) ?>" />
	<input type="hidden" name="oauthState" value="<?php p($_['oauthState']) ?>" />
	<input id="submit-redirect-form" type="submit" class="hidden "/>
</form>

Remove old button to submit the apppassword login

Signed-off-by: John Molakvoæ (skjnldsv) <0835dbafb601d1e4088d26d0286d7121ba48453b@protonmail.com>


<?php

/**
 * This file is part of the ValueObjects package.
 *
 * (c) Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 */

namespace ValueObjects\Enum;

use MyCLabs\Enum\Enum;
use ValueObjects\ValueObjectInterface;

/**
 * Class AbstractEnum.
 *
 * @package ValueObjects
 * @author  Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 * @link    http://github.com/lorenzomar/valueobjects
 */
abstract class AbstractEnum extends Enum implements ValueObjectInterface
{
    public function sameValueAs(ValueObjectInterface $valueObject)
    {
        return $this == $valueObject;
    }

    public function copy()
    {
        return clone $this;
    }

    public function __clone()
    {
        return new static($this->getValue());
    }
}

<?php

/**
 * This file is part of the ValueObject package.
 *
 * (c) Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 */

namespace ValueObject\Enum;

use MyCLabs\Enum\Enum;
use ValueObject\SimpleValueObjectInterface;
use ValueObject\ValueObjectInterface;

/**
 * Class AbstractEnum.
 *
 * @package ValueObject
 * @author  Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 * @link    http://github.com/lorenzomar/valueobjects
 */
abstract class AbstractEnum extends Enum implements SimpleValueObjectInterface
{
    public function value()
    {
        return $this->getValue();
    }

    public function sameValueAs(ValueObjectInterface $valueObject)
    {
        return $this == $valueObject;
    }

    public function copy()
    {
        return clone $this;
    }

    public function __clone()
    {
        return new static($this->value());
    }
}

Update namespace and implement SimpleValueObject


<?php
namespace Concrete\Core\Config;

use Illuminate\Config\FileLoader;
use Illuminate\Filesystem\Filesystem;

class ConfigLoader extends FileLoader {

    protected $config;

    public function __construct(Filesystem $files, Config $config) {
        $this->config = $config;
        parent::__construct($files, DIR_APPLICATION . '/config');
        $this->addNamespace('core', DIR_BASE . '/concrete/config');
    }

    public function load($environment, $group, $namespace = null)
    {
        if (is_null($namespace)) {
            return array_replace_recursive(
                parent::load($environment, $group, 'core'),
                parent::load($environment, $group, $namespace)
                (array) parent::load($environment, $group, 'core'),
                (array) parent::load($environment, $group, $namespace)
            );
        }
        return parent::load($environment, $group, $namespace);
    }

}

<?php
namespace Concrete\Core\Config;

use Illuminate\Config\FileLoader;
use Illuminate\Filesystem\Filesystem;

class ConfigLoader extends FileLoader {

    protected $config;

    public function __construct(Filesystem $files, Config $config) {
        $this->config = $config;
        parent::__construct($files, DIR_APPLICATION . '/config');
        $this->addNamespace('core', DIR_BASE . '/concrete/config');
    }

    public function load($environment, $group, $namespace = null)
    {
        if (is_null($namespace)) {
            return array_replace_recursive(
                (array) parent::load($environment, $group, 'core'),
                (array) parent::load($environment, $group, $namespace)
            );
        }
        return parent::load($environment, $group, $namespace);
    }

}

Convert everything other than assets to app config

We're using Laravel's config resolving classes:

```PHP
$config = $app->make('config');
$config->get('app.version'); // '5.7.0b2'
```

Former-commit-id: 950db1326fe3a417acb509d4d2b572fda0cdd100


<?php

namespace Stack;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class JsonRequest implements HttpKernelInterface
{
    private $app;
    private $contentTypes = array('application/json');

    public function __construct(HttpKernelInterface $app, array $contentTypes = array())
    {
        $this->app = $app;
    }

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        if (in_array($request->headers->get('Content-Type'), $this->contentTypes, true)) {
            $data = json_decode($request->getContent(), true);
            $request->request->replace(is_array($data) ? $data : array());
        }

        return $this->app->handle($request, $type, $catch);
    }
}

<?php

namespace Stack;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;

class JsonRequest implements HttpKernelInterface, TerminableInterface
{
    private $app;
    private $contentType;

    public function __construct(HttpKernelInterface $app, $contentType = 'application/json')
    {
        $this->app = $app;
        $this->contentType = $contentType;
    }

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        if (0 === strpos($request->headers->get('Content-Type'), $this->contentType)) {
            $data = json_decode($request->getContent(), true);
            $request->request->replace(is_array($data) ? $data : array());
        }

        return $this->app->handle($request, $type, $catch);
    }

    public function terminate(Request $request, Response $response)
    {
        $request->headers->set('Content-Type', $this->contentType);
        $request->headers->set('Accept', $this->contentType);

        if ($this->app instanceof TerminableInterface) {
            $this->app->terminate($request, $response);
        }
    }
}

Fix and add terminate to set Content-Type and Accept header


<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Controllers\InterOp;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserGroupsController extends Controller
{
    public function update()
    {
        [$user, $group] = $this->getUserAndGroupModels();
        $modes = get_param_value(request()->input('modes'), 'string[]');

        $user->addOrUpdateGroup($group, $modes);

        return response(null, 204);
    }

    public function destroy()
    {
        [$user, $group] = $this->getUserAndGroupModels();

        $user->removeFromGroup($group);

        return response(null, 204);
    }

    public function setDefault()
    {
        [$user, $group] = $this->getUserAndGroupModels();

        $user->setDefaultGroup($group);

        return response(null, 204);
    }

    private function getUserAndGroupModels()
    {
        $params = get_params(request()->all(), null, [
            'group_id:int',
            'user_id:int',
        ]);

        $group = app('groups')->byId($params['group_id'] ?? null);
        abort_if($group === null, 404, 'Group not found');

        return [
            User::findOrFail($params['user_id'] ?? null),
            $group,
        ];
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Http\Controllers\InterOp;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserGroupsController extends Controller
{
    public function update()
    {
        [$user, $group] = $this->getUserAndGroupModels();
        $modes = get_arr(request()->input('playmodes'), 'get_string');

        $user->addOrUpdateGroup($group, $modes);

        return response(null, 204);
    }

    public function destroy()
    {
        [$user, $group] = $this->getUserAndGroupModels();

        $user->removeFromGroup($group);

        return response(null, 204);
    }

    public function setDefault()
    {
        [$user, $group] = $this->getUserAndGroupModels();

        $user->setDefaultGroup($group);

        return response(null, 204);
    }

    private function getUserAndGroupModels()
    {
        $params = get_params(request()->all(), null, [
            'group_id:int',
            'user_id:int',
        ]);

        $group = app('groups')->byId($params['group_id'] ?? null);
        abort_if($group === null, 404, 'Group not found');

        return [
            User::findOrFail($params['user_id'] ?? null),
            $group,
        ];
    }
}

Rename modes param to playmodes and use get_arr directly


<?php
namespace Zend\Config;

use Zend\ServiceManager\AbstractPluginManager;

class WriterPluginManager extends AbstractPluginManager
{
    protected $invokableClasses = array(
        'php'  => 'Zend\Config\Writer\PhpArray',
        'ini'  => 'Zend\Config\Writer\Ini',
        'json' => 'Zend\Config\Writer\Json',
        'yaml' => 'Zend\Config\Writer\Yaml',
        'xml'  => 'Zend\Config\Writer\Xml',
    );

    public function validatePlugin($plugin)
    {
        if ($plugin instanceOf Writer\AbstractWriter) {
            return;
        }

        $type = is_object($plugin) ? get_class($plugin) : gettype($plugin);

        throw new Exception\InvalidArgumentException(
            "Plugin of type {$type} is invalid. Plugin must extend ".
                __NAMESPACE__.'\Writer\AbstractWriter'
        );
    }
}

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

namespace Zend\Config;

use Zend\ServiceManager\AbstractPluginManager;

class WriterPluginManager extends AbstractPluginManager
{
    protected $invokableClasses = array(
        'php'  => 'Zend\Config\Writer\PhpArray',
        'ini'  => 'Zend\Config\Writer\Ini',
        'json' => 'Zend\Config\Writer\Json',
        'yaml' => 'Zend\Config\Writer\Yaml',
        'xml'  => 'Zend\Config\Writer\Xml',
    );

    public function validatePlugin($plugin)
    {
        if ($plugin instanceOf Writer\AbstractWriter) {
            return;
        }

        $type = is_object($plugin) ? get_class($plugin) : gettype($plugin);

        throw new Exception\InvalidArgumentException(
            "Plugin of type {$type} is invalid. Plugin must extend ".
                __NAMESPACE__.'\Writer\AbstractWriter'
        );
    }
}

Add missing file level doc-block

Add missing file level doc-block


<?php
class Kwc_Basic_LinkTag_FirstChildPage_Data extends Kwf_Component_Data
{
    private $_pageCache = false;
    public function __get($var)
    {
        if ($var == 'url') {
            $page = $this->_getFirstChildPage();
            return $page ? $page->url : '';
        } else if ($var == 'rel') {
            $page = $this->_getFirstChildPage();
            return $page ? $page->rel : '';
        } else {
            return parent::__get($var);
        }
    }

    public function getAbsoluteUrl()
    {
        return $this->_getFirstChildPage()->getAbsoluteUrl();
    }

    public function _getFirstChildPage()
    {
        if ($this->_pageCache === false) {
            // zuerst prüfen ob es eine händisch angelegte child page gibt
            $page = $this->getChildPage(array('pageGenerator' => true));
            if (!$page) {
                $page = $this->getChildPage(array('inherit'=>false),
                                        array(
                                            'inherit'=>false,
                                            'page'=>false
                                        ));
            }
            $this->_pageCache = $page;
        }
        return $this->_pageCache;
    }

    public function getLinkDataAttributes()
    {
        return $this->_getFirstChildPage()->getLinkDataAttributes();
    }

}

<?php
class Kwc_Basic_LinkTag_FirstChildPage_Data extends Kwf_Component_Data
{
    private $_pageCache = false;
    public function __get($var)
    {
        if ($var == 'url') {
            $page = $this->_getFirstChildPage();
            return $page ? $page->url : '';
        } else if ($var == 'rel') {
            $page = $this->_getFirstChildPage();
            return $page ? $page->rel : '';
        } else {
            return parent::__get($var);
        }
    }

    public function getAbsoluteUrl()
    {
        $page = $this->_getFirstChildPage();
        return $page ? $page->getAbsoluteUrl() : '';
    }

    public function _getFirstChildPage()
    {
        if ($this->_pageCache === false) {
            // zuerst prüfen ob es eine händisch angelegte child page gibt
            $page = $this->getChildPage(array('pageGenerator' => true));
            if (!$page) {
                $page = $this->getChildPage(array('inherit'=>false),
                                        array(
                                            'inherit'=>false,
                                            'page'=>false
                                        ));
            }
            $this->_pageCache = $page;
        }
        return $this->_pageCache;
    }

    public function getLinkDataAttributes()
    {
        $page = $this->_getFirstChildPage();
        return $page ? $page->getLinkDataAttributes() : array();
    }

}

Fix FirstChildPage if child page doesn't exist


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

<!DOCTYPE html>

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

		<?php makeNav();?>

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

				";
				exit(0);
			}?>

What is PodTube?

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

How Does This Work?

Sign up for an account to get started.

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

Development

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

Add basic homepage for unauthenticated users


<?php

// change the following paths if necessary
$yii=dirname(__FILE__).'/../../../yii/framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';

// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
defined('PUB_IS_PAYPAL_LIVE') or define('PUB_IS_PAYPAL_LIVE',true);

// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);

require_once($yii);
Yii::createWebApplication($config)->run();

echo md5('2'.'token_141030_1641');

Add file to test .

Add file to test .