Deploy continuo com jenkins, codeception e zend server
-
Upload
william-felipe -
Category
Technology
-
view
330 -
download
6
Transcript of Deploy continuo com jenkins, codeception e zend server
DEPLOY CONTINUO COM JENKINS,CODECEPTION E ZEND SERVER
Created by William Felipe Welter
#WHOAMIWILLIAM FELIPE WELTER
Líder da equipe de inovação PHP da 4LinuxBacharel em Ciência da ComputaçãoExperiência com desenvolvimento e infraestrutura
O QUE É DEPLOY CONTINUO ?
CONTINOUS DEPLOY != CONTINOUSDELIVERY
CONTINOUS DEPLOYCommit/PushBuild PipelineDeploy
CONTINOUS DELIVERYCodigo "pronto" para produçãoNão necessariamente precisa realizar deploy
CONTINOUS DEPLOY DEPENDE DE C.DELIVERY
Commitou vai para produção !Codigo precisa estar testadoProcedimentos precisam ser automatizados
MAS O QUE É CONTINOUS DELIVERY?
Aplicação ser testavelCodigo sempre utilizavelPipelineAutomatizaçãoEntregas constantes!
MAS QUAL A VANTAGEM?Agilidade no desenvolvimentoDeploys menos "doloridos"Não podemos ter medo do Deploy!Grandes deploys = grande instabilidadeDeploys curtos = menor probabilidade de bugsAgilidade em correção de bugsNovidades constantes = Estar na frenteRapido feedback sobre novas features
E QUEM TRABALHA ASSIM ?AmazonFacebookYahooGoogleNetflix
DEVOPS
AGILE
FERRAMENTAS
VERSIONAMENTO/REPOSITORIO DECÓDIGO
GIT
FRAMEWORK DE TESTESCodeception
INTEGRAÇÃO CONTINUAJenkins
DEPLOY AUTOMATIZADOZend Server
MIGRAÇÕES DE BANCO DE DADOSPhinx
GIT
CRIANDO SEU REPOSITORIOLocalGitLabGitHubBitbucket
GITHUBRegistre-seCrie seu repositorioClone o repositorio
$ git clone https://github.com/wfelipew/phpconf2015.gitCloning into 'phpconf2015'...remote: Counting objects: 3, done.remote: Total 3 (delta 0), reused 0 (delta 0), packreused 0Unpacking objects: 100% (3/3), done.Checking connectivity... done.
DEFINIR BRANCHESDesenvolvimento -developHomologação - homologProdução - master
CRIANDO NOVAS BRANCHS $ git branch develop$ git checkout develop Switched to branch 'develop'$ git push origin develop Username for 'https://github.com': [email protected] for 'https://[email protected]@github.com': Total 0 (delta 0), reused 0 (delta 0)To https://github.com/wfelipew/phpconf2015.git * [new branch] develop > develop
FLUXO DE DESENVOLVIMENTONovas historias(features) -> developCorreção de bugs -> homolog -> developCada historia pode ficar em uma branch até ficar estavelNa master só pode ter codigo pronto para produção
CODECEPTION
FRAMEWORK DE TESTESUnitario - Regras de negocioAceitação - Principais fluxos de usoFuncional - Estressar fluxos de usoAPI - Aceitação/Funcional
COMPATIVEL COM:ZF1ZF2Symfony 2Laravel 4Laravel 5Phalcon 1Phalcon 2Doctrine 2SilexYii 1Yii 2...
INSTALAR:
$ wget http://codeception.com/codecept.phar
INICIALIZAR DIRETORIO:
$ codecept.phar bootstrap Initializing Codeception in cartCheckout/phpconf2015/src
File codeception.yml created < global configurationtests/unit created < unit teststests/unit.suite.yml written < unit tests suite configurationtests/functional created < functional teststests/functional.suite.yml written < functional tests suite configurationtests/acceptance created < acceptance teststests/acceptance.suite.yml written < acceptance tests suite configurationtests/_output was added to .gitignore tests/_bootstrap.php written < global bootstrap fileBuilding initial Tester classesBuilding Actor classes for suites: unit, acceptance, functional > UnitTesterActions.php generated successfully. 0 methods added\UnitTester includes modules: Asserts, \Helper\UnitUnitTester.php created. > AcceptanceTesterActions.php generated successfully. 0 methods added\AcceptanceTester includes modules: PhpBrowser, \Helper\AcceptanceAcceptanceTester.php created. > FunctionalTesterActions.php generated successfully. 0 methods added\FunctionalTester includes modules: \Helper\FunctionalFunctionalTester.php created.
FunctionalTester.php created.
Bootstrap is done. Check out cartCheckout/phpconf2015/src/tests directory
APLICAÇÃO DE EXEMPLOAPIZF2Carrinho de compras
REGRAS DE NEGOCIOAdicionar itemAtualizar itemRemover itemObter um itemObter todo o carrinhoLimpar o carrinhoValor totalPersistir em sessão
VAMOS CODIFICAR ?
TDD
CRIAR O TESTE UNITARIO:
$ codecept generate:test unit CartTest was created in cartCheckout/phpconf2015/src/tests/unit/CartTest.php
CONFIGURAR ACESSO AO ZF2
# Codeception Test Suite Configuration## Suite for unit (internal) tests.
class_name: UnitTestermodules: enabled: Asserts \Helper\Unit ZF2 Asserts
unit.suite.yml
CONFIGURAR ACESSO AO ZF2
return array( 'modules' => array( 'Application', ), 'module_listener_options' => array( 'module_paths' => array( __DIR__ . '/../module', __DIR__ . '/../vendor', ), 'config_glob_paths' => array( __DIR__ . '/../config/autoload/,*.global,local.php', ), 'config_cache_enabled'=>false, 'module_map_cache_enabled'=>false, 'check_dependencies'=>true, ),);
application.config.php
CRIANDO O TESTE:
use Application\Model\CartModel;use Zend\Session\Container;
class CartTest extends \Codeception\TestCase\Test
/** * * @var \UnitTester */ protected $model;
protected function _before() $container = new Container(); $this>model = new CartModel($container);
protected function _after() // tests
// tests
public function testAddItem() $item = array( 'id' => '212', 'price' => '42.42', 'qty' => 1 ); $this>model>addItem($item); $this>assertInternalType("array", $this>model>getCart()); $this>assertCount(1, $this>model>getCart());
public function testUpdateItem() $item = array( 'id' => '212', 'price' => '42.42', 'qty' => 3 ); $this>model>updateItem(212, $item); $this>assertCount(1, $this>model>getCart()); $updatedItem = $this>model>getItem(212); $this>assertEquals(3, $updatedItem['qty']);
public function testDeleteItem() $this>model>deleteItem(212); $this>assertCount(0, $this>model>getCart()); $this>assertArrayNotHasKey(212,$this>model>getCart());
$this>assertArrayNotHasKey(212,$this>model>getCart());
public function testTotalCart() $item1 = array( 'id' => '212', 'price' => 1, 'qty' => 3 ); $item2 = array( 'id' => '32', 'price' => 5.50, 'qty' => 1 ); $this>model>addItem($item1); $this>model>addItem($item2); $this>assertCount(2, $this>model>getCart()); $this>assertEquals(8.50, $this>model>getTotalAmount()); public function testCleanCart() $this>model>cleanCart(); $this>assertCount(0, $this>model>getCart());
CRIANDO A CLASSE NO ZF2
namespace Application\Model;
use Zend\Session\Container;
class CartModel
private $cart;
public function __construct(Container $cart)
public function addItem($item)
public function updateItem($id, $item)
public function deleteItem($id)
public function getItem($id)
public function getCart()
public function getTotalAmount()
public function cleanCart()
EXECUTANDO TESTES:
$ codecept.phar runCodeception PHP Testing Framework v2.1.4Powered by PHPUnit 4.8.18 by Sebastian Bergmann and contributors.Unit Tests (5) Test add item (CartTest::testAddItem) ErrorTest update item (CartTest::testUpdateItem) ErrorTest delete item (CartTest::testDeleteItem) ErrorTest total cart (CartTest::testTotalCart) ErrorTest clean cart (CartTest::testCleanCart) Error
Acceptance Tests (0)
Functional Tests (0)
Time: 1,96 seconds, Memory: 21,00Mb
There were 5 errors:
IMPLEMENTANDO A MODEL
namespace Application\Model;
use Zend\Session\Container;
class CartModel
private $cart;
public function __construct(Container $cart) $this>cart = $cart; if (! isset($this>cart>item)) $this>cart>item = array();
public function addItem($item) $id = $item['id']; unset($item['id']); $this>cart>item[$id] = $item;
public function updateItem($id, $item)
public function updateItem($id, $item)
unset($item['id']); $this>cart>item[$id] = $item;
public function deleteItem($id) unset($this>cart>item[$id]);
public function getItem($id) if (isset($this>cart>item[$id])) return $this>cart>item[$id]; else return false;
public function getCart() if (! $this>cart>item) $this>cart>item = array(); return $this>cart>item;
public function getTotalAmount() $total = 0;
$total = 0;
foreach ($this>cart>item as $item) $total += $item['price'] * $item['qty']; return $total;
public function cleanCart() $this>cart>item = null;
RODAR NOVAMENTE OS TESTES
codecept.phar runCodeception PHP Testing Framework v2.1.4Powered by PHPUnit 4.8.18 by Sebastian Bergmann and contributors.
Unit Tests (5) Test add item (CartTest::testAddItem) OkTest update item (CartTest::testUpdateItem) OkTest delete item (CartTest::testDeleteItem) OkTest total cart (CartTest::testTotalCart) OkTest clean cart (CartTest::testCleanCart) Ok
Acceptance Tests (0)
Functional Tests (0)
Time: 2,96 seconds, Memory: 20,25Mb
OK (5 tests, 9 assertions)
CRIAR TESTE DE API
$ codecept.php generate:cest api Cart
CONFIGURANDO ACESSO AAPI/WEBSERVER/BROWSER
class_name: ApiTestermodules: enabled: REST: url: http://phpconf2015.local/ depends: PhpBrowserenv: local: modules: config: PhpBrowser: url: http://phpconf2015.local/ curl: CURLOPT_TIMEOUT: 600 connect_timeout: 600 timeout: 600 REST: url: http://phpconf2015.local/ dev: modules: config:
config:
PhpBrowser: url: http://phpconf2015dev.local/ curl: CURLOPT_TIMEOUT: 600 connect_timeout: 600 timeout: 600 REST: url: http://phpconf2015dev.local/ homolog: modules: config: PhpBrowser: url: http://phpconf2015homolog.local/ curl: CURLOPT_TIMEOUT: 600 connect_timeout: 600 timeout: 600 REST: url: http://phpconf2015homolog.local/
api.suite.yml
CODIFICANDO O TESTE
use \ApiTester;
class CartCest
private $cookie;
private function getCookie() $cookie = $this>cookie; $cookie = implode(' ', $this>cookie); $cookie = preg_replace('/path=\//', '', $cookie); return $cookie;
public function _before(ApiTester $I) // Clean cart // $I>sendDELETE('api/cart');
public function _after(ApiTester $I)
// tests public function tryToTest(ApiTester $I)
public function testAddItemCart(ApiTester $I) $I>wantTo('Insert add item to cart'); $I>haveHttpHeader('ContentType', 'application/json'); $I>sendPOST('api/cart', array( 'id' => 212, 'qty' => 3, 'price' => 3.5 )); $I>seeResponseCodeIs(200); $I>seeResponseIsJson(); $this>cookie = $I>grabHttpHeader('SetCookie', false);
public function testGetCart(ApiTester $I) $I>wantTo('Get all item of a cart'); $I>haveHttpHeader('ContentType', 'application/json'); $I>haveHttpHeader('Cookie', $this>getCookie()); $I>sendGET('api/cart'); $I>seeResponseCodeIs(200); $I>seeResponseIsJson(); $I>seeResponseContainsJson(array( '212' => array(
'212' => array(
'qty' => 3, 'price' => 3.5 ) ));
public function testUpdateItem(ApiTester $I) $I>wantTo('Update item on cart'); $I>haveHttpHeader('ContentType', 'application/json'); $I>haveHttpHeader('Cookie', $this>getCookie()); $I>sendPUT('api/cart/212', array( 'id' => 212, 'qty' => 9, 'price' => 3.5 )); $I>seeResponseCodeIs(200); $I>seeResponseIsJson(); $I>seeResponseContainsJson(array( '212' => array( 'qty' => 9, 'price' => 3.5 ) ));
public function testGetItem(ApiTester $I) $I>wantTo('Get item from cart');
$I>wantTo('Get item from cart');
$I>haveHttpHeader('ContentType', 'application/json'); $I>haveHttpHeader('Cookie', $this>getCookie()); $I>sendGET('api/cart/212'); $I>seeResponseCodeIs(200); $I>seeResponseIsJson(); $I>seeResponseContainsJson(array( 'qty' => 9, 'price' => 3.5 ));
public function testDeleteItem(ApiTester $I) $I>wantTo('Remove item from cart'); $I>haveHttpHeader('ContentType', 'application/json'); $I>haveHttpHeader('Cookie', $this>getCookie()); $I>sendDELETE('api/cart/212'); $I>seeResponseCodeIs(200); $I>seeResponseIsJson(); $I>seeResponseContainsJson(array()); public function testClearCart(ApiTester $I) $I>wantTo('Clear cart'); $I>haveHttpHeader('ContentType', 'application/json'); $I>haveHttpHeader('Cookie', $this>getCookie()); $I>sendPOST('api/cart', array(
$I>sendPOST('api/cart', array(
'id' => 212, 'qty' => 3, 'price' => 3.5 )); $I>sendPOST('api/cart', array( 'id' => 214, 'qty' => 1, 'price' => 7.5 )); $I>sendDELETE('api/cart'); $I>seeResponseCodeIs(200); $I>seeResponseIsJson(); $I>seeResponseContainsJson(array()); public function testGetInvalidItem(ApiTester $I) $I>wantTo('Get invalid item from cart'); $I>haveHttpHeader('ContentType', 'application/json'); $I>haveHttpHeader('Cookie', $this>getCookie()); $I>sendGET('api/cart/500'); $I>seeResponseCodeIs(400); $I>seeResponseIsJson(); $I>seeResponseContainsJson(array());
CRIANDO A CONTROLLER
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;use Zend\View\Model\JsonModel;
class CartController extends AbstractRestfulController
public function create($data) $cartModel = $this>serviceLocator>get('CartModel'); $cartModel>addItem($data); return new JsonModel($cartModel>getCart());
public function update($id, $data) $cartModel = $this>serviceLocator>get('CartModel'); $cartModel>updateItem($id, $data); return new JsonModel($cartModel>getCart());
public function delete($id)
public function delete($id)
$cartModel = $this>serviceLocator>get('CartModel'); $cartModel>deleteItem($id); return new JsonModel($cartModel>getCart());
public function get($id) $cartModel = $this>serviceLocator>get('CartModel'); $item = $cartModel>getItem($id); if (!$item) $this>response>setStatusCode(400); $item = array(); return new JsonModel($item);
public function getList() $cartModel = $this>serviceLocator>get('CartModel'); $cart = $cartModel>getCart(); return new JsonModel($cart);
public function deleteList() $cartModel = $this>serviceLocator>get('CartModel'); $cartModel>cleanCart(); $cart = $cartModel>getCart();
$cart = $cartModel>getCart();
return new JsonModel($cart);
RODANDO O TESTE
codecept.phar runCodeception PHP Testing Framework v2.1.4Powered by PHPUnit 4.8.18 by Sebastian Bergmann and contributors.
Api Tests (9) Try to test (CartCest::tryToTest) OkInsert add item to cart (CartCest::testAddItemCart) OkGet all item of a cart (CartCest::testGetCart) OkUpdate item on cart (CartCest::testUpdateItem) OkGet item from cart (CartCest::testGetItem) OkRemove item from cart (CartCest::testDeleteItem) OkClear cart (CartCest::testClearCart) OkGet invalid item from cart (CartCest::testGetInvalidItem) OkPerform actions and see result (CartCept) Ok
Unit Tests (5) Test add item (CartTest::testAddItem) OkTest update item (CartTest::testUpdateItem) OkTest delete item (CartTest::testDeleteItem) OkTest total cart (CartTest::testTotalCart) OkTest clean cart (CartTest::testCleanCart) Ok
Acceptance Tests (0)
Functional Tests (0)
Time: 2,96 seconds, Memory: 20,25Mb
OK (14 tests, 29 assertions)
DEPLOY
PACOTE ZPKPadronizar deployVersãoParametrizaçãoArquivos a serem deployadosRotinas a serem executadas em cada fase do deployDependenciasConfigurações de ambienteRegras de monitoramentoRegras de cacheVia webconsole ou API
DEPLOYMENT.XML
DEPLOYMENT.XML - DEPENDENCIAS
DEPLOYMENT.XML - ROTINAS EPARAMETRIZAÇÃO
REGRAS DE MONITORAMENTO
DEPLOY - CONSOLE WEB
ZSCLIENT.PHARFerrament CLI para trabalhar com APIEmpacotarDeploy.zsapi
OBTENDO CHAVE PARA API:
.ZSAPI [zendlocal]zsurl = "http://localhost:10081"zskey = "admin"zssecret = "asdadaskdamdlkasmdek3mk4343k4tmrkrmfkgk556565m6k56m56k5mgrsr44kg"zsversion = "8.0"http.timeout = "300"
EXEMPLO zsclient.phar installApp zpk=application.zpk target=awsprod baseUri=
JENKINS
CI Open SourceFlexivelPluginsBuild Pipeline
PHP-TEMPLATETemplate para aplicações PHPANTDepende de varios pluginsDepende de algumas ferramentas PHP
PHP-TEMPLATEphplocphpmdphpcsphpunitphpdoxphpcbphpcpdpdepend
INSTALANDO
$ wget http://localhost:8080/jnlpJars/jenkinscli.jar$ java jar jenkinscli.jar s http://localhost:8080 installplugin checkstyle cloverphp crap4j dry htmlpublisher jdepend plot pmd violations warnings xunit$ curl L https://raw.githubusercontent.com/sebastianbergmann/phpjenkinstemplate/master/config.xml | \ java jar jenkinscli.jar s http://localhost:8080 createjob phptemplate $ java jar jenkinscli.jar s http://localhost:8080 reloadconfiguration
BUILD.XML
<project name="phpconf2015" default="buildlocal"> <target name="buildlocal" depends="prepare,lint,package,phploc,pdepend,phpmdci,phpcsci,phpcpd,phpdox,phpcb,composer,codeception" <target name="builddevelop" depends="prepare,lint,package,deploydev,phploc,pdepend,phpmdci,phpcsci,phpcpd,phpdox,phpcb,composer,codeception" <target name="buildhomolog" depends="prepare,lint,package,deployhomolog,phploc,pdepend,phpmdci,phpcsci,phpcpd,phpdox,phpcb,composer,codeceptionhomolog" <target name="buildmaster" depends="prepare,lint,package,deployprod"
<target name="buildparallel" depends="prepare,lint,toolsparallel,phpunit,phpcb"
<target name="toolsparallel" description="Run tools in parallel" <parallel threadCount="2"> <sequential> <antcall target="pdepend" /> <antcall target="phpmdci" /> </sequential> <antcall target="phpcpd" /> <antcall target="phpcsci" /> <antcall target="phploc" /> <antcall target="phpdox" /> </parallel> </target>
<target name="clean" description="Cleanup build artifacts">
<target name="clean" description="Cleanup build artifacts">
<delete dir="$basedir/build/api" /> <delete dir="$basedir/build/codebrowser" /> <delete dir="$basedir/build/coverage" /> <delete dir="$basedir/build/logs" /> <delete dir="$basedir/build/pdepend" /> </target>
<target name="prepare" depends="clean" description="Prepare for build" <mkdir dir="$basedir/build/api" /> <mkdir dir="$basedir/build/codebrowser" /> <mkdir dir="$basedir/build/coverage" /> <mkdir dir="$basedir/build/logs" /> <mkdir dir="$basedir/build/pdepend" /> <mkdir dir="$basedir/build/phpdox" />
<mkdir dir="$basedir/build/log" /> <mkdir dir="$basedir/build/cache" /> <mkdir dir="$basedir/build/tmp_certificados" /> <mkdir dir="$basedir/build/tmp_spool_swift" /> <chmod dir="$basedir/build/log" perm="777" /> <chmod dir="$basedir/build/cache" perm="777" /> <chmod dir="$basedir/build/tmp_certificados" perm="777" <chmod dir="$basedir/build/tmp_spool_swift" perm="777" </target>
<target name="lint" description="Perform syntax check of sourcecode files" <apply executable="php" failonerror="true"> <arg value="l" />
<fileset dir="$basedir">
<fileset dir="$basedir">
<include name="**/*.php" /> <exclude name="src/vendor/" /> <exclude name="vendor/" /> <exclude name="vendor/*" /> <exclude name="data/generator/" /> <modified /> </fileset>
</apply> </target>
<target name="phploc" description="Measure project size using PHPLOC" <exec executable="phploc"> <arg value="exclude=" /> <arg value="vendor" /> <arg value="exclude=" /> <arg value="tests" /> <arg value="logcsv" /> <arg value="$basedir/build/logs/phploc.csv" <arg path="$basedir" /> </exec> </target>
<target name="pdepend" description="Calculate software metrics using PHP_Depend" <exec executable="pdepend"> <arg value="jdependxml=$basedir/build/logs/jdepend.xml" <arg value="jdependchart=$basedir/build/pdepend/dependencies.svg" <arg value="overviewpyramid=$basedir/build/pdepend/overviewpyramid.svg" <arg value="ignore=$basedir/scripts/,$basedir/src/vendor/,$basedir/src/data/"
<arg value="ignore=$basedir/scripts/,$basedir/src/vendor/,$basedir/src/data/"
<arg path="$basedir" /> </exec> </target>
<target name="phpmd" description="Perform project mess detection using PHPMD and print human readable output. Intended for usage on the command line before committing." <exec executable="phpmd"> <arg path="$basedir" /> <arg value="text" /> <arg value="$basedir/build/phpmd.xml" /> <arg value="exclude=$basedir/lib/vendor/,$basedir/data/,$basedir/scripts/" </exec> </target>
<target name="phpmdci" description="Perform project mess detection using PHPMD creating a log file for the continuous integration server" <exec executable="phpmd"> <arg path="$basedir" /> <arg value="xml" /> <arg value="$basedir/build/phpmd.xml" /> <arg value="reportfile" /> <arg value="$basedir/build/logs/pmd.xml" /> <arg value="exclude" /> <arg value="*scripts*,*vendor*,*tests*,*data*" </exec> </target>
<target name="package" description="Package with ZPK"> <exec executable="zsclient.phar" failonerror="true"> <arg value="packZpk" /> <arg value="folder=$basedir" /> <arg value="destination=$basedir" />
<arg value="destination=$basedir" />
<arg value="name=application.zpk" /> </exec> </target>
<target name="phpcs" description="Find coding standard violations using PHP_CodeSniffer and print human readable output. Intended for usage on the command line before committing." <exec executable="phpcs"> <arg value="standard=$basedir/build/phpcs.xml" <arg path="$basedir" /> <arg value="ignore=$basedir/tests" /> </exec> </target>
<target name="phpcsci" description="Find coding standard violations using PHP_CodeSniffer creating a log file for the continuous integration server" <exec executable="phpcs" output="/dev/null"> <arg value="extensions=php" /> <arg value="v" /> <arg value="report=checkstyle" /> <arg value="reportfile=$basedir/build/logs/checkstyle.xml" <arg value="standard=$basedir/build/phpcs.xml" <arg value="ignore=$basedir/src/vendor/,$basedir/scripts/,$basedir/src/tests/,$basedir/src/data/" <arg path="$basedir" /> </exec> </target>
<target name="phpcpd" description="Find duplicate code using PHPCPD" <exec executable="phpcpd"> <arg value="exclude" /> <arg value="scripts" /> <arg value="exclude" />
<arg value="exclude" />
<arg value="vendor" /> <arg value="exclude" /> <arg value="tests" /> <arg value="logpmd" /> <arg value="$basedir/build/logs/pmdcpd.xml" <arg path="$basedir" /> </exec> </target>
<target name="phpdox" description="Generate API documentation using phpDox" <exec executable="phpdox"> <arg line="file $basedir/build/phpdox.xml" </exec> </target>
<target name="phpunit" description="Run unit tests with PHPUnit" <exec executable="phpunit" failonerror="true" /> </target>
<target name="deploydev" description="Deploy on ZendServer"> <exec executable="zsclient.phar" failonerror="true"> <arg value="installApp" /> <arg value="zpk=$basedir/application.zpk" <arg value="target=zendlocal" /> <arg value="baseUri='http://phpconf2015dev.local/'" <arg value="userAppName=phpconf2015dev" /> </exec> </target>
<target name="deployprod" description="Package with ZPK"> <exec executable="zsclient.phar" failonerror="true"> <arg value="installApp" /> <arg value="zpk=$basedir/application.zpk" <arg value="target=zendlocal" /> <arg value="baseUri='http://phpconf2015prod.local/'" <arg value="userAppName=phpconf2015prod" /> </exec> </target> <target name="deployhomolog" description="Package with ZPK"> <exec executable="zsclient.phar" failonerror <arg value="installApp" /> <arg value="zpk=$basedir/application.zpk" <arg value="target=zendlocal" /> <arg value="baseUri='http://phpconf2015homolog.local/'" <arg value="userAppName=phpconf2015homolog" </exec> </target>
<target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser" <exec executable="phpcb"> <arg value="log" /> <arg path="$basedir/build/logs" /> <arg value="source" /> <arg path="$basedir" /> <arg value="output" /> <arg path="$basedir/build/codebrowser" />
<arg path="$basedir/build/codebrowser" />
<arg value="exclude=" /> <arg value="*/vendor/*" /> <arg value="exclude=" /> <arg value="*/tests/*" /> <arg value="exclude=" /> <arg value="*/build/*" /> </exec> </target>
<target name="composer"> <exec executable="php" failonerror="true"> <arg line="composer.phar install workingdir=$basedir/src" </exec> </target>
<target name="codeception"> <exec executable="codecept.phar" failonerror="true"> <arg line=" run config=src/codeception.yml env dev steps xml html" </exec> </target> <target name="codeceptionhomolog"> <exec executable="codecept.phar" failonerror= <arg line=" run config=src/codeception.yml env homolog steps xml html" </exec> </target>
</project>
BUILD.XML - LINT
<target name="lint" description="Perform syntax check of sourcecode files" <apply executable="php" failonerror="true"> <arg value="l" />
<fileset dir="$basedir"> <include name="**/*.php" /> <exclude name="src/vendor/" /> <exclude name="vendor/*" /> <exclude name="data/generator/" /> <modified /> </fileset>
</apply></target>
BUILD.XML - PHPLOC
<target name="phploc" description="Measure project size using PHPLOC" <exec executable="phploc"> <arg value="exclude=" /> <arg value="vendor" /> <arg value="exclude=" /> <arg value="tests" /> <arg value="logcsv" /> <arg value="$basedir/build/logs/phploc.csv" /> <arg path="$basedir" /> </exec></target>
BUILD.XML - PDEPEND
<target name="pdepend" description="Calculate software metrics using PHP_Depend" <exec executable="pdepend"> <arg value="jdependxml=$basedir/build/logs/jdepend.xml" <arg value="jdependchart=$basedir/build/pdepend/dependencies.svg" <arg value="overviewpyramid=$basedir/build/pdepend/overviewpyramid.svg" <arg value="ignore=$basedir/scripts/,$basedir/src/vendor/,$basedir/src/data/" <arg path="$basedir" /> </exec></target>
BUILD.XML - PHPMD-CI
<target name="phpmdci" description="Perform project mess detection using PHPMD creating a log file for the continuous integration server" <exec executable="phpmd"> <arg path="$basedir" /> <arg value="xml" /> <arg value="$basedir/build/phpmd.xml" /> <arg value="reportfile" /> <arg value="$basedir/build/logs/pmd.xml" /> <arg value="exclude" /> <arg value="*scripts*,*vendor*,*tests*,*data*" /> </exec></target>
BUILD/PHPMD.XML
<?xml version="1.0" encoding="UTF8"?><ruleset name="Regras phpconf2015" xmlns="http://pmd.sf.net/ruleset/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd" xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd" <description>Padroes a serem utilizados no phpconf2015</description
<rule ref="rulesets/codesize.xml/CyclomaticComplexity" /> <rule ref="rulesets/codesize.xml/ExcessiveMethodLength" /> <rule ref="rulesets/codesize.xml/ExcessiveClassLength" /> <rule ref="rulesets/codesize.xml/ExcessiveClassComplexity" /> <rule ref="rulesets/codesize.xml/ExcessiveParameterList" /> <rule ref="rulesets/design.xml/GotoStatement" /> <rule ref="rulesets/design.xml/ExitExpression" /> <rule ref="rulesets/design.xml/EvalExpression" /> <rule ref="rulesets/design.xml/CouplingBetweenObjects" /> <rule ref="rulesets/design.xml/DepthOfInheritance" /> <rule ref="rulesets/design.xml/NumberOfChildren" /> <rule ref="rulesets/naming.xml/ShortMethodName" /> <rule ref="rulesets/naming.xml/BooleanGetMethodName" /> <rule ref="rulesets/controversial.xml/Superglobals" />
</ruleset>
BUILD.XML - PHPCS-CI
<target name="phpcsci" description="Find coding standard violations using PHP_CodeSniffer creating a log file for the continuous integration server" <exec executable="phpcs" output="/dev/null"> <arg value="extensions=php" /> <arg value="v" /> <arg value="report=checkstyle" /> <arg value="reportfile=$basedir/build/logs/checkstyle.xml" <arg value="standard=$basedir/build/phpcs.xml" /> <arg value="ignore=$basedir/src/vendor/,$basedir/scripts/,$basedir/src/tests/,$basedir/src/data/" <arg path="$basedir" /> </exec></target>
BUILD/PHPCS.XML
<?xml version="1.0" encoding="UTF8"?><ruleset name="phpconf2015"> <description>Regras de codigo do phpconf2015</description>
<rule ref="PSR2"/> <rule ref="Generic.PHP.DisallowShortOpenTag"/> <rule ref="Generic.PHP.LowerCaseConstant"/> <rule ref="Generic.CodeAnalysis.UnconditionalIfStatement"/>
</ruleset>
BUILD.XML - PHPCPD
<target name="phpcpd" description="Find duplicate code using PHPCPD"> <exec executable="phpcpd"> <arg value="exclude" /> <arg value="scripts" /> <arg value="exclude" /> <arg value="vendor" /> <arg value="exclude" /> <arg value="tests" /> <arg value="logpmd" /> <arg value="$basedir/build/logs/pmdcpd.xml" /> <arg path="$basedir" /> </exec></target>
BUILD.XML - PHPDOX
<target name="phpdox" description="Generate API documentation using phpDox" <exec executable="phpdox"> <arg line="file $basedir/build/phpdox.xml" /> </exec></target>
BUILD/PHPDOX.XML
<?xml version="1.0" encoding="UTF8"?><phpdox xmlns="http://xml.phpdox.net/config"> <project name="phpconf2015" source="." workdir="build/phpdox"> <collector publiconly="false"> <include mask="*.php" /> <exclude mask="*Autoload.php" /> <exclude mask="**vendor**" /> <exclude mask="**scripts**" /> <exclude mask="**build**" /> <exclude mask="**tests**" /> </collector>
<generator output="build"> <build engine="html" enabled="true" output="api"/> </generator> </project></phpdox>
BUILD.XML - PHPCB
<target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser" <exec executable="phpcb"> <arg value="log" /> <arg path="$basedir/build/logs" /> <arg value="source" /> <arg path="$basedir" /> <arg value="output" /> <arg path="$basedir/build/codebrowser" /> <arg value="exclude=" /> <arg value="*/vendor/*" /> <arg value="exclude=" /> <arg value="*/tests/*" /> <arg value="exclude=" /> <arg value="*/build/*" /> </exec></target>
BUILD.XML - COMPOSER
<target name="composer"> <exec executable="php" failonerror="true"> <arg line="composer.phar install workingdir=$basedir/src" </exec></target>
BUILD.XML - CODECEPTION
<target name="codeception"> <exec executable="codecept.phar" failonerror="true"> <arg line=" run config=src/codeception.yml env dev steps xml html" </exec></target>
SAIDA DO CODECEPTION
actor: Testerpaths: tests: tests log: tests/_output data: tests/_data support: tests/_support envs: tests/_envssettings: bootstrap: _bootstrap.php colors: true memory_limit: 1024M strict_xml: trueextensions: enabled: Codeception\Extension\RunFailedmodules: config: Db: dsn: '' user: '' password: '' dump: tests/_data/dump.sql
BUILD.XML - PACKAGE
<target name="package" description="Package with ZPK"> <exec executable="zsclient.phar" failonerror="true"> <arg value="packZpk" /> <arg value="folder=$basedir" /> <arg value="destination=$basedir" /> <arg value="name=application.zpk" /> </exec></target>
BUILD.XML - DEPLOY
<target name="deploydev" description="Deploy on ZendServer"> <exec executable="zsclient.phar" failonerror="true"> <arg value="installApp" /> <arg value="zpk=$basedir/application.zpk" /> <arg value="target=zendlocal" /> <arg value="baseUri='http://phpconf2015dev.local/'" <arg value="userAppName=phpconf2015dev" /> </exec></target>
PHINX
Migrações de banco de dadosSimplesMulti-SGBD
INSTALAR
$ php composer.phar require robmorgan/phinx$ php composer.phar install nodev$ php vendor/bin/phinx init .
CONFIGURAÇÃO
paths: migrations: %%PHINX_CONFIG_DIR%%/migrations
environments: default_migration_table: phinxlog default_database: production production: adapter: pgsql host: localhost name: phpconf2015_prod user: phpconf2015_prod pass: '123456' port: 5432 charset: utf8
homolog: adapter: pgsql host: localhost name: phpconf2015_homolog user: phpconf2015_homolog pass: '123456' port: 5432 charset: utf8
development: adapter: pgsql host: localhost name: phpconf2015_local user: phpconf2015_local pass: '123456' port: 5432 charset: utf8
phinx.yml
CRIANDO UMA MIGRAÇÃO
$ php vendor/bin/phinx create AddTableOrdersPhinx by Rob Morgan https://phinx.org. version 0.5.0
using config file ./phinx.ymlusing config parser yamlusing migration path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/migrationsusing seed path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/seedsusing migration base class Phinx\Migration\AbstractMigrationusing default templatecreated ./db/migrations/20151202195430_add_table_orders.php
EDITANDO A MIGRAÇÃO - CHANGE
use Phinx\Migration\AbstractMigration;
class AddTableOrders extends AbstractMigration public function change() $table=$this>table('tb_orders_item'); $table>addColumn('product_id','integer') >addColumn('qty','integer') >addColumn('price','float'); $table>create();
db/migrations/20151202195430_add_table_orders.php
EDITANDO A MIGRAÇÃO - UP/DOWN
class AddTableUsers extends AbstractMigration public function up() $table = $this>table('tb_users'); $table>addColumn('email', 'string') >addColumn('password', 'string') >addColumn('active', 'boolean'); $table>create(); $this>execute("INSERT INTO tb_users(email,password,active) VALUES ('[email protected]',md5('123456'),'t')"
public function down() $table = $this>dropTable('tb_users');
db/migrations/20151202195430_add_table_orders.php
APLICANDO MIGRAÇÃO
$ php vendor/bin/phinx migratePhinx by Rob Morgan https://phinx.org. version 0.5.0
using config file ./phinx.ymlusing config parser yamlusing migration path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/migrationsusing seed path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/seedswarning no environment specified, defaulting to: developmentusing adapter pgsqlusing database phpconf2015
== 20151202195430 AddTableOrders: migrating == 20151202195430 AddTableOrders: migrated 0,0979s
== 20151202201703 AddTableUsers: migrating == 20151202201703 AddTableUsers: migrated 0,1120s
All Done. Took 0,2231s
CONSULTANDO ESTADO DASMIGRACÕES
$ php vendor/bin/phinx statusPhinx by Rob Morgan https://phinx.org. version 0.5.0
using config file ./phinx.ymlusing config parser yamlusing migration path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/migrationsusing seed path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/seedswarning no environment specified, defaulting to: development
Status Migration ID Migration Name up 20151202195430 AddTableOrders down 20151202201703 AddTableUsers
REVERTENDO UMA MIGRAÇÃO
$ php vendor/bin/phinx rollbackPhinx by Rob Morgan https://phinx.org. version 0.5.0
using config file ./phinx.ymlusing config parser yamlusing migration path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/migrationsusing seed path /home/williamwelter/Documents/area_php/apresentacoes/php_conf_2015/cartCheckout/phpconf2015/src/db/seedswarning no environment specified, defaulting to: developmentusing adapter pgsqlusing database phpconf2015
== 20151202201703 AddTableUsers: reverting == 20151202201703 AddTableUsers: reverted 0,0488s
All Done. Took 0,0622s
COMO AUTOMATIZAR ?Deploy Zend ServerScript preActivate