diff --git a/.gitignore b/.gitignore index 94d08a876b..5e79bef4c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/database/backups /database/data /database/migrations/extras /legacy diff --git a/.scrutinizer.yml b/.scrutinizer.yml index fbe848f5b8..45f4184e5b 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -27,18 +27,19 @@ tools: build: environment: - postgresql: true variables: APP_ENV: 'testing' DB_CONNECTION: 'pgsql' DB_HOST: 'localhost' DB_PORT: '5432' - DB_DATABASE: 'ieducar_test' + DB_DATABASE: 'scrutinizer' DB_USERNAME: 'scrutinizer' DB_PASSWORD: 'scrutinizer' dependencies: before: - - psql -c "CREATE DATABASE ieducar_test WITH OWNER = scrutinizer ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' TEMPLATE template0" + - composer new-install tests: override: command: "true" + services: + postgres: 9.5 diff --git a/app/Console/Commands/DatabaseRestoreCommand.php b/app/Console/Commands/DatabaseRestoreCommand.php new file mode 100644 index 0000000000..3c94eef9b2 --- /dev/null +++ b/app/Console/Commands/DatabaseRestoreCommand.php @@ -0,0 +1,222 @@ + %s'; + + $command = sprintf( + $definition, + $filename, + $this->getDatabaseList() + ); + + passthru($command); + } + + /** + * Remove lines that contains table data imports. + * + * @param array $tables + * + * @return void + */ + private function removeTableDataFromDatabaseList(array $tables) + { + foreach ($tables as $table) { + $table = str_replace('.', ' ', $table); + + $definition = 'sed -i \'/TABLE DATA %s/d\' %s'; + + $command = sprintf( + $definition, + $table, + $this->getDatabaseList(), + $this->getDatabaseList() + ); + + passthru($command); + } + } + + /** + * Return audit tables. + * + * @return array + */ + private function getAuditTables() + { + return [ + 'modules.auditoria', + 'modules.auditoria_geral', + 'pmieducar.auditoria_falta_componente_dispensa', + 'pmieducar.auditoria_nota_dispensa', + ]; + } + + /** + * Drop old database if exists and create it again. + * + * @param string $database + * + * @return void + */ + private function dropAndCreateDatabase($database) + { + $definition = 'echo "drop database if exists %s; create database %s;" | psql -h %s -p %s -U %s'; + + $command = sprintf( + $definition, + $database, + $database, + $this->getHost(), + $this->getPort(), + $this->getUser() + ); + + passthru($command); + } + + /** + * Restore the database using the backup file. + * + * @param string $database + * @param string $filename + * + * @return void + */ + private function restoreDatabaseUsingBackupFile($database, $filename) + { + $definition = 'pg_restore -L %s --host=%s --port=%s --username=%s --dbname=%s %s'; + + $command = sprintf( + $definition, + $this->getDatabaseList(), + $this->getHost(), + $this->getPort(), + $this->getUser(), + $database, + $filename + ); + + passthru($command); + } + + /** + * Alter search path for database. Use legacy i-Educar configuration. + * + * @param string $database + * + * @return void + */ + private function alterSearchPathInDatabase($database) + { + $definition = 'echo "ALTER DATABASE %s SET search_path = \"\$user\", public, portal, cadastro, acesso, alimentos, consistenciacao, historico, pmiacoes, pmicontrolesis, pmidrh, pmieducar, pmiotopic, urbano, modules;" | psql -h %s -p %s -U %s'; + + $command = sprintf( + $definition, + $database, + $this->getHost(), + $this->getPort(), + $this->getUser() + ); + + passthru($command); + } + + /** + * Delete the database list created. + * + * @return void + */ + private function deleteDatabaseList() + { + if (file_exists($this->getDatabaseList())) { + unlink($this->getDatabaseList()); + } + } + + /** + * Execute the console command. + * + * @return mixed + */ + public function handle() + { + $database = $this->argument('database'); + $filename = $this->argument('filename'); + + $this->createDatabaseList($filename); + $this->removeTableDataFromDatabaseList($this->getAuditTables()); + $this->dropAndCreateDatabase($database); + $this->restoreDatabaseUsingBackupFile($database, $filename); + $this->alterSearchPathInDatabase($database); + $this->deleteDatabaseList(); + } +} diff --git a/composer.json b/composer.json index 2850bab35d..e1dc9b48cc 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "description": "Software livre de gestão escolar", "type": "project", "license": "GPL-2.0-or-later", - "version": "2.1.0", + "version": "2.1.1", "keywords": [ "Portabilis", "i-Educar" @@ -15,6 +15,7 @@ "cocur/slugify": "^3.1", "composer/semver": "^1.4", "cossou/jasperphp": "^2.7", + "doctrine/dbal": "^2.9", "fideloper/proxy": "^4.0", "google/recaptcha": "^1.2", "honeybadger-io/honeybadger-laravel": "^1.4", diff --git a/composer.lock b/composer.lock index 08c1ee922a..e32fd4a5fc 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "9f3d6951d6c36cc5f2e923ac66041fe2", + "content-hash": "3f27d4bd5852bf8c314626a1d7672f18", "packages": [ { "name": "cocur/slugify", @@ -207,6 +207,237 @@ "description": "implementation of xdg base directory specification for php", "time": "2014-10-24T07:27:01+00:00" }, + { + "name": "doctrine/cache", + "version": "v1.8.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/cache.git", + "reference": "d768d58baee9a4862ca783840eca1b9add7a7f57" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/cache/zipball/d768d58baee9a4862ca783840eca1b9add7a7f57", + "reference": "d768d58baee9a4862ca783840eca1b9add7a7f57", + "shasum": "" + }, + "require": { + "php": "~7.1" + }, + "conflict": { + "doctrine/common": ">2.2,<2.4" + }, + "require-dev": { + "alcaeus/mongo-php-adapter": "^1.1", + "doctrine/coding-standard": "^4.0", + "mongodb/mongodb": "^1.1", + "phpunit/phpunit": "^7.0", + "predis/predis": "~1.0" + }, + "suggest": { + "alcaeus/mongo-php-adapter": "Required to use legacy MongoDB driver" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\Cache\\": "lib/Doctrine/Common/Cache" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "Caching library offering an object-oriented API for many cache backends", + "homepage": "https://www.doctrine-project.org", + "keywords": [ + "cache", + "caching" + ], + "time": "2018-08-21T18:01:43+00:00" + }, + { + "name": "doctrine/dbal", + "version": "v2.9.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/dbal.git", + "reference": "ec74d6e300d78fbc896669c3ca57ef9719adc9c6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/dbal/zipball/ec74d6e300d78fbc896669c3ca57ef9719adc9c6", + "reference": "ec74d6e300d78fbc896669c3ca57ef9719adc9c6", + "shasum": "" + }, + "require": { + "doctrine/cache": "^1.0", + "doctrine/event-manager": "^1.0", + "ext-pdo": "*", + "php": "^7.1" + }, + "require-dev": { + "doctrine/coding-standard": "^5.0", + "jetbrains/phpstorm-stubs": "^2018.1.2", + "phpstan/phpstan": "^0.10.1", + "phpunit/phpunit": "^7.4", + "symfony/console": "^2.0.5|^3.0|^4.0", + "symfony/phpunit-bridge": "^3.4.5|^4.0.5" + }, + "suggest": { + "symfony/console": "For helpful console commands such as SQL execution and import of files." + }, + "bin": [ + "bin/doctrine-dbal" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.9.x-dev", + "dev-develop": "3.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\DBAL\\": "lib/Doctrine/DBAL" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + } + ], + "description": "Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.", + "homepage": "https://www.doctrine-project.org/projects/dbal.html", + "keywords": [ + "abstraction", + "database", + "dbal", + "mysql", + "persistence", + "pgsql", + "php", + "queryobject" + ], + "time": "2018-12-14T04:51:13+00:00" + }, + { + "name": "doctrine/event-manager", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/event-manager.git", + "reference": "a520bc093a0170feeb6b14e9d83f3a14452e64b3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/event-manager/zipball/a520bc093a0170feeb6b14e9d83f3a14452e64b3", + "reference": "a520bc093a0170feeb6b14e9d83f3a14452e64b3", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "conflict": { + "doctrine/common": "<2.9@dev" + }, + "require-dev": { + "doctrine/coding-standard": "^4.0", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\": "lib/Doctrine/Common" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + }, + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com" + } + ], + "description": "Doctrine Event Manager component", + "homepage": "https://www.doctrine-project.org/projects/event-manager.html", + "keywords": [ + "event", + "eventdispatcher", + "eventmanager" + ], + "time": "2018-06-11T11:59:03+00:00" + }, { "name": "doctrine/inflector", "version": "v1.3.0", @@ -379,16 +610,16 @@ }, { "name": "egulias/email-validator", - "version": "2.1.6", + "version": "2.1.7", "source": { "type": "git", "url": "https://github.com/egulias/EmailValidator.git", - "reference": "0578b32b30b22de3e8664f797cf846fc9246f786" + "reference": "709f21f92707308cdf8f9bcfa1af4cb26586521e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/0578b32b30b22de3e8664f797cf846fc9246f786", - "reference": "0578b32b30b22de3e8664f797cf846fc9246f786", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/709f21f92707308cdf8f9bcfa1af4cb26586521e", + "reference": "709f21f92707308cdf8f9bcfa1af4cb26586521e", "shasum": "" }, "require": { @@ -432,7 +663,7 @@ "validation", "validator" ], - "time": "2018-09-25T20:47:26+00:00" + "time": "2018-12-04T22:38:24+00:00" }, { "name": "erusev/parsedown", @@ -699,32 +930,33 @@ }, { "name": "guzzlehttp/psr7", - "version": "1.4.2", + "version": "1.5.2", "source": { "type": "git", "url": "https://github.com/guzzle/psr7.git", - "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c" + "reference": "9f83dded91781a01c63574e387eaa769be769115" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/psr7/zipball/f5b8a8512e2b58b0071a7280e39f14f72e05d87c", - "reference": "f5b8a8512e2b58b0071a7280e39f14f72e05d87c", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/9f83dded91781a01c63574e387eaa769be769115", + "reference": "9f83dded91781a01c63574e387eaa769be769115", "shasum": "" }, "require": { "php": ">=5.4.0", - "psr/http-message": "~1.0" + "psr/http-message": "~1.0", + "ralouphie/getallheaders": "^2.0.5" }, "provide": { "psr/http-message-implementation": "1.0" }, "require-dev": { - "phpunit/phpunit": "~4.0" + "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.4-dev" + "dev-master": "1.5-dev" } }, "autoload": { @@ -754,37 +986,37 @@ "keywords": [ "http", "message", + "psr-7", "request", "response", "stream", "uri", "url" ], - "time": "2017-03-20T17:10:46+00:00" + "time": "2018-12-04T20:46:45+00:00" }, { "name": "honeybadger-io/honeybadger-laravel", - "version": "v1.4.0", + "version": "v1.5.0", "source": { "type": "git", "url": "https://github.com/honeybadger-io/honeybadger-laravel.git", - "reference": "5ae5a13e05a8e9dc2080e05a3d2e2995aff8d310" + "reference": "40140b63f4df85a61a52034d921eb0d221332973" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/honeybadger-io/honeybadger-laravel/zipball/5ae5a13e05a8e9dc2080e05a3d2e2995aff8d310", - "reference": "5ae5a13e05a8e9dc2080e05a3d2e2995aff8d310", + "url": "https://api.github.com/repos/honeybadger-io/honeybadger-laravel/zipball/40140b63f4df85a61a52034d921eb0d221332973", + "reference": "40140b63f4df85a61a52034d921eb0d221332973", "shasum": "" }, "require": { "honeybadger-io/honeybadger-php": "^1.2", "illuminate/console": "^5.5", "illuminate/support": "^5.5", - "php": "^7.1|7.2", + "php": "^7.1", "sixlive/dotenv-editor": "^1.1" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^2.10", "larapack/dd": "^1.0", "mockery/mockery": "^1.1", "orchestra/testbench": "^3.5", @@ -830,29 +1062,28 @@ "logging", "monitoring" ], - "time": "2018-11-02T15:52:07+00:00" + "time": "2018-12-17T11:15:03+00:00" }, { "name": "honeybadger-io/honeybadger-php", - "version": "v1.2.1", + "version": "v1.3.0", "source": { "type": "git", "url": "https://github.com/honeybadger-io/honeybadger-php.git", - "reference": "8e48346bb125592630fe784ba8eae9a948900be2" + "reference": "7cb54d64eb82ce84d4ec664818e2832769086caf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/honeybadger-io/honeybadger-php/zipball/8e48346bb125592630fe784ba8eae9a948900be2", - "reference": "8e48346bb125592630fe784ba8eae9a948900be2", + "url": "https://api.github.com/repos/honeybadger-io/honeybadger-php/zipball/7cb54d64eb82ce84d4ec664818e2832769086caf", + "reference": "7cb54d64eb82ce84d4ec664818e2832769086caf", "shasum": "" }, "require": { "guzzlehttp/guzzle": "^6.3", - "php": "^7.1|^7.2", + "php": "^7.1", "symfony/http-foundation": ">=3.3 || ^4.1" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^2.10", "mockery/mockery": "^1.1", "phpunit/phpunit": "^7.0" }, @@ -885,7 +1116,7 @@ "logging", "monitoring" ], - "time": "2018-11-08T14:02:53+00:00" + "time": "2018-12-17T11:11:31+00:00" }, { "name": "jakub-onderka/php-console-color", @@ -977,16 +1208,16 @@ }, { "name": "laravel/framework", - "version": "v5.7.15", + "version": "v5.7.19", "source": { "type": "git", "url": "https://github.com/laravel/framework.git", - "reference": "e0dbd6ab143286d81bedf2b34f8820f3d49ea15f" + "reference": "5c1d1ec7e8563ea31826fd5eb3f6791acf01160c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/framework/zipball/e0dbd6ab143286d81bedf2b34f8820f3d49ea15f", - "reference": "e0dbd6ab143286d81bedf2b34f8820f3d49ea15f", + "url": "https://api.github.com/repos/laravel/framework/zipball/5c1d1ec7e8563ea31826fd5eb3f6791acf01160c", + "reference": "5c1d1ec7e8563ea31826fd5eb3f6791acf01160c", "shasum": "" }, "require": { @@ -995,6 +1226,8 @@ "erusev/parsedown": "^1.7", "ext-mbstring": "*", "ext-openssl": "*", + "laravel/nexmo-notification-channel": "^1.0", + "laravel/slack-notification-channel": "^1.0", "league/flysystem": "^1.0.8", "monolog/monolog": "^1.12", "nesbot/carbon": "^1.26.3", @@ -1117,7 +1350,121 @@ "framework", "laravel" ], - "time": "2018-11-26T14:10:57+00:00" + "time": "2018-12-18T14:00:38+00:00" + }, + { + "name": "laravel/nexmo-notification-channel", + "version": "v1.0.1", + "source": { + "type": "git", + "url": "https://github.com/laravel/nexmo-notification-channel.git", + "reference": "03edd42a55b306ff980c9950899d5a2b03260d48" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/nexmo-notification-channel/zipball/03edd42a55b306ff980c9950899d5a2b03260d48", + "reference": "03edd42a55b306ff980c9950899d5a2b03260d48", + "shasum": "" + }, + "require": { + "nexmo/client": "^1.0", + "php": "^7.1.3" + }, + "require-dev": { + "illuminate/notifications": "~5.7", + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + }, + "laravel": { + "providers": [ + "Illuminate\\Notifications\\NexmoChannelServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Illuminate\\Notifications\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Nexmo Notification Channel for laravel.", + "keywords": [ + "laravel", + "nexmo", + "notifications" + ], + "time": "2018-12-04T12:57:08+00:00" + }, + { + "name": "laravel/slack-notification-channel", + "version": "v1.0.3", + "source": { + "type": "git", + "url": "https://github.com/laravel/slack-notification-channel.git", + "reference": "6e164293b754a95f246faf50ab2bbea3e4923cc9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/slack-notification-channel/zipball/6e164293b754a95f246faf50ab2bbea3e4923cc9", + "reference": "6e164293b754a95f246faf50ab2bbea3e4923cc9", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "^6.0", + "php": "^7.1.3" + }, + "require-dev": { + "illuminate/notifications": "~5.7", + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + }, + "laravel": { + "providers": [ + "Illuminate\\Notifications\\SlackChannelServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Illuminate\\Notifications\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Slack Notification Channel for laravel.", + "keywords": [ + "laravel", + "notifications", + "slack" + ], + "time": "2018-12-12T13:12:06+00:00" }, { "name": "laravel/tinker", @@ -1182,6 +1529,64 @@ ], "time": "2018-10-12T19:39:35+00:00" }, + { + "name": "lcobucci/jwt", + "version": "3.2.5", + "source": { + "type": "git", + "url": "https://github.com/lcobucci/jwt.git", + "reference": "82be04b4753f8b7693b62852b7eab30f97524f9b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lcobucci/jwt/zipball/82be04b4753f8b7693b62852b7eab30f97524f9b", + "reference": "82be04b4753f8b7693b62852b7eab30f97524f9b", + "shasum": "" + }, + "require": { + "ext-openssl": "*", + "php": ">=5.5" + }, + "require-dev": { + "mdanter/ecc": "~0.3.1", + "mikey179/vfsstream": "~1.5", + "phpmd/phpmd": "~2.2", + "phpunit/php-invoker": "~1.1", + "phpunit/phpunit": "~4.5", + "squizlabs/php_codesniffer": "~2.3" + }, + "suggest": { + "mdanter/ecc": "Required to use Elliptic Curves based algorithms." + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.1-dev" + } + }, + "autoload": { + "psr-4": { + "Lcobucci\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Luís Otávio Cobucci Oblonczyk", + "email": "lcobucci@gmail.com", + "role": "developer" + } + ], + "description": "A simple library to work with JSON Web Token and JSON Web Signature", + "keywords": [ + "JWS", + "jwt" + ], + "time": "2018-11-11T12:22:26+00:00" + }, { "name": "league/flysystem", "version": "1.0.49", @@ -1402,6 +1807,54 @@ ], "time": "2018-11-22T18:23:02+00:00" }, + { + "name": "nexmo/client", + "version": "1.6.0", + "source": { + "type": "git", + "url": "https://github.com/Nexmo/nexmo-php.git", + "reference": "01809cc1e17a5af275913c49bb5d444eb6cc06d4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nexmo/nexmo-php/zipball/01809cc1e17a5af275913c49bb5d444eb6cc06d4", + "reference": "01809cc1e17a5af275913c49bb5d444eb6cc06d4", + "shasum": "" + }, + "require": { + "lcobucci/jwt": "^3.2", + "php": ">=5.6", + "php-http/client-implementation": "^1.0", + "php-http/guzzle6-adapter": "^1.0", + "zendframework/zend-diactoros": "^1.3" + }, + "require-dev": { + "estahn/phpunit-json-assertions": "^1.0.0", + "php-http/mock-client": "^0.3.0", + "phpunit/phpunit": "^5.7", + "squizlabs/php_codesniffer": "^3.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "Nexmo\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Tim Lytle", + "email": "tim@nexmo.com", + "homepage": "http://twitter.com/tjlytle", + "role": "Developer" + } + ], + "description": "PHP Client for using Nexmo's API.", + "time": "2018-12-17T10:47:50+00:00" + }, { "name": "nikic/php-parser", "version": "v4.1.0", @@ -1455,16 +1908,16 @@ }, { "name": "opis/closure", - "version": "3.1.1", + "version": "3.1.2", "source": { "type": "git", "url": "https://github.com/opis/closure.git", - "reference": "d3209e46ad6c69a969b705df0738fd0dbe26ef9e" + "reference": "de00c69a2328d3ee5baa71fc584dc643222a574c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/opis/closure/zipball/d3209e46ad6c69a969b705df0738fd0dbe26ef9e", - "reference": "d3209e46ad6c69a969b705df0738fd0dbe26ef9e", + "url": "https://api.github.com/repos/opis/closure/zipball/de00c69a2328d3ee5baa71fc584dc643222a574c", + "reference": "de00c69a2328d3ee5baa71fc584dc643222a574c", "shasum": "" }, "require": { @@ -1472,7 +1925,7 @@ }, "require-dev": { "jeremeamia/superclosure": "^2.0", - "phpunit/phpunit": "^4.0" + "phpunit/phpunit": "^4.0|^5.0|^6.0|^7.0" }, "type": "library", "extra": { @@ -1512,7 +1965,7 @@ "serialization", "serialize" ], - "time": "2018-10-02T13:36:53+00:00" + "time": "2018-12-16T21:48:23+00:00" }, { "name": "paragonie/random_compat", @@ -1559,6 +2012,172 @@ ], "time": "2018-07-02T15:55:56+00:00" }, + { + "name": "php-http/guzzle6-adapter", + "version": "v1.1.1", + "source": { + "type": "git", + "url": "https://github.com/php-http/guzzle6-adapter.git", + "reference": "a56941f9dc6110409cfcddc91546ee97039277ab" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/guzzle6-adapter/zipball/a56941f9dc6110409cfcddc91546ee97039277ab", + "reference": "a56941f9dc6110409cfcddc91546ee97039277ab", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "^6.0", + "php": ">=5.5.0", + "php-http/httplug": "^1.0" + }, + "provide": { + "php-http/async-client-implementation": "1.0", + "php-http/client-implementation": "1.0" + }, + "require-dev": { + "ext-curl": "*", + "php-http/adapter-integration-tests": "^0.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2-dev" + } + }, + "autoload": { + "psr-4": { + "Http\\Adapter\\Guzzle6\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + }, + { + "name": "David de Boer", + "email": "david@ddeboer.nl" + } + ], + "description": "Guzzle 6 HTTP Adapter", + "homepage": "http://httplug.io", + "keywords": [ + "Guzzle", + "http" + ], + "time": "2016-05-10T06:13:32+00:00" + }, + { + "name": "php-http/httplug", + "version": "v1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/httplug.git", + "reference": "1c6381726c18579c4ca2ef1ec1498fdae8bdf018" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/httplug/zipball/1c6381726c18579c4ca2ef1ec1498fdae8bdf018", + "reference": "1c6381726c18579c4ca2ef1ec1498fdae8bdf018", + "shasum": "" + }, + "require": { + "php": ">=5.4", + "php-http/promise": "^1.0", + "psr/http-message": "^1.0" + }, + "require-dev": { + "henrikbjorn/phpspec-code-coverage": "^1.0", + "phpspec/phpspec": "^2.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Eric GELOEN", + "email": "geloen.eric@gmail.com" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "HTTPlug, the HTTP client abstraction for PHP", + "homepage": "http://httplug.io", + "keywords": [ + "client", + "http" + ], + "time": "2016-08-31T08:30:17+00:00" + }, + { + "name": "php-http/promise", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/promise.git", + "reference": "dc494cdc9d7160b9a09bd5573272195242ce7980" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/promise/zipball/dc494cdc9d7160b9a09bd5573272195242ce7980", + "reference": "dc494cdc9d7160b9a09bd5573272195242ce7980", + "shasum": "" + }, + "require-dev": { + "henrikbjorn/phpspec-code-coverage": "^1.0", + "phpspec/phpspec": "^2.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Http\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + }, + { + "name": "Joel Wurtz", + "email": "joel.wurtz@gmail.com" + } + ], + "description": "Promise used for asynchronous HTTP requests", + "homepage": "http://httplug.io", + "keywords": [ + "promise" + ], + "time": "2016-01-26T13:27:02+00:00" + }, { "name": "psr/container", "version": "1.0.0", @@ -1827,6 +2446,46 @@ ], "time": "2018-10-13T15:16:03+00:00" }, + { + "name": "ralouphie/getallheaders", + "version": "2.0.5", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/5601c8a83fbba7ef674a7369456d12f1e0d0eafa", + "reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa", + "shasum": "" + }, + "require": { + "php": ">=5.3" + }, + "require-dev": { + "phpunit/phpunit": "~3.7.0", + "satooshi/php-coveralls": ">=1.0" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "time": "2016-02-11T07:05:27+00:00" + }, { "name": "ramsey/uuid", "version": "3.8.0", @@ -2020,7 +2679,7 @@ }, { "name": "symfony/console", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/console.git", @@ -2089,16 +2748,16 @@ }, { "name": "symfony/contracts", - "version": "v1.0.0", + "version": "v1.0.2", "source": { "type": "git", "url": "https://github.com/symfony/contracts.git", - "reference": "4a33574d5771f4b04334cd4f7d43de96a92efb62" + "reference": "1aa7ab2429c3d594dd70689604b5cf7421254cdf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/contracts/zipball/4a33574d5771f4b04334cd4f7d43de96a92efb62", - "reference": "4a33574d5771f4b04334cd4f7d43de96a92efb62", + "url": "https://api.github.com/repos/symfony/contracts/zipball/1aa7ab2429c3d594dd70689604b5cf7421254cdf", + "reference": "1aa7ab2429c3d594dd70689604b5cf7421254cdf", "shasum": "" }, "require": { @@ -2153,11 +2812,11 @@ "interoperability", "standards" ], - "time": "2018-10-31T08:00:32+00:00" + "time": "2018-12-05T08:06:11+00:00" }, { "name": "symfony/css-selector", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", @@ -2210,7 +2869,7 @@ }, { "name": "symfony/debug", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/debug.git", @@ -2266,16 +2925,16 @@ }, { "name": "symfony/event-dispatcher", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "9b788b5f7cd6be22918f3d18ee3ff0a78e060137" + "reference": "921f49c3158a276d27c0d770a5a347a3b718b328" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/9b788b5f7cd6be22918f3d18ee3ff0a78e060137", - "reference": "9b788b5f7cd6be22918f3d18ee3ff0a78e060137", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/921f49c3158a276d27c0d770a5a347a3b718b328", + "reference": "921f49c3158a276d27c0d770a5a347a3b718b328", "shasum": "" }, "require": { @@ -2326,11 +2985,11 @@ ], "description": "Symfony EventDispatcher Component", "homepage": "https://symfony.com", - "time": "2018-11-26T10:55:26+00:00" + "time": "2018-12-01T08:52:38+00:00" }, { "name": "symfony/finder", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", @@ -2379,7 +3038,7 @@ }, { "name": "symfony/http-foundation", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", @@ -2433,22 +3092,22 @@ }, { "name": "symfony/http-kernel", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "500409e5d8a31fc92450a0ec2ea4e4c35af40117" + "reference": "b39ceffc0388232c309cbde3a7c3685f2ec0a624" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/500409e5d8a31fc92450a0ec2ea4e4c35af40117", - "reference": "500409e5d8a31fc92450a0ec2ea4e4c35af40117", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/b39ceffc0388232c309cbde3a7c3685f2ec0a624", + "reference": "b39ceffc0388232c309cbde3a7c3685f2ec0a624", "shasum": "" }, "require": { "php": "^7.1.3", "psr/log": "~1.0", - "symfony/contracts": "^1.0", + "symfony/contracts": "^1.0.2", "symfony/debug": "~3.4|~4.0", "symfony/event-dispatcher": "~4.1", "symfony/http-foundation": "^4.1.1", @@ -2518,7 +3177,7 @@ ], "description": "Symfony HttpKernel Component", "homepage": "https://symfony.com", - "time": "2018-11-30T09:16:14+00:00" + "time": "2018-12-06T17:39:52+00:00" }, { "name": "symfony/polyfill-ctype", @@ -2694,7 +3353,7 @@ }, { "name": "symfony/process", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/process.git", @@ -2743,16 +3402,16 @@ }, { "name": "symfony/routing", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/routing.git", - "reference": "97b9f457df748357eec101df5c8b1c649b543241" + "reference": "649460207e77da6c545326c7f53618d23ad2c866" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/routing/zipball/97b9f457df748357eec101df5c8b1c649b543241", - "reference": "97b9f457df748357eec101df5c8b1c649b543241", + "url": "https://api.github.com/repos/symfony/routing/zipball/649460207e77da6c545326c7f53618d23ad2c866", + "reference": "649460207e77da6c545326c7f53618d23ad2c866", "shasum": "" }, "require": { @@ -2816,25 +3475,25 @@ "uri", "url" ], - "time": "2018-11-29T14:48:32+00:00" + "time": "2018-12-03T22:08:12+00:00" }, { "name": "symfony/translation", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "ff9a878c9b8f8bcd4d9138e2d32f508c942773d9" + "reference": "c0e2191e9bed845946ab3d99767513b56ca7dcd6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/ff9a878c9b8f8bcd4d9138e2d32f508c942773d9", - "reference": "ff9a878c9b8f8bcd4d9138e2d32f508c942773d9", + "url": "https://api.github.com/repos/symfony/translation/zipball/c0e2191e9bed845946ab3d99767513b56ca7dcd6", + "reference": "c0e2191e9bed845946ab3d99767513b56ca7dcd6", "shasum": "" }, "require": { "php": "^7.1.3", - "symfony/contracts": "^1.0", + "symfony/contracts": "^1.0.2", "symfony/polyfill-mbstring": "~1.0" }, "conflict": { @@ -2889,11 +3548,11 @@ ], "description": "Symfony Translation Component", "homepage": "https://symfony.com", - "time": "2018-11-27T07:20:32+00:00" + "time": "2018-12-06T10:45:32+00:00" }, { "name": "symfony/var-dumper", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", @@ -3062,6 +3721,70 @@ "environment" ], "time": "2018-07-29T20:33:41+00:00" + }, + { + "name": "zendframework/zend-diactoros", + "version": "1.8.6", + "source": { + "type": "git", + "url": "https://github.com/zendframework/zend-diactoros.git", + "reference": "20da13beba0dde8fb648be3cc19765732790f46e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/20da13beba0dde8fb648be3cc19765732790f46e", + "reference": "20da13beba0dde8fb648be3cc19765732790f46e", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0", + "psr/http-message": "^1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "ext-dom": "*", + "ext-libxml": "*", + "php-http/psr7-integration-tests": "dev-master", + "phpunit/phpunit": "^5.7.16 || ^6.0.8 || ^7.2.7", + "zendframework/zend-coding-standard": "~1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8.x-dev", + "dev-develop": "1.9.x-dev", + "dev-release-2.0": "2.0.x-dev" + } + }, + "autoload": { + "files": [ + "src/functions/create_uploaded_file.php", + "src/functions/marshal_headers_from_sapi.php", + "src/functions/marshal_method_from_sapi.php", + "src/functions/marshal_protocol_version_from_sapi.php", + "src/functions/marshal_uri_from_sapi.php", + "src/functions/normalize_server.php", + "src/functions/normalize_uploaded_files.php", + "src/functions/parse_cookie_header.php" + ], + "psr-4": { + "Zend\\Diactoros\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "description": "PSR HTTP Message implementations", + "homepage": "https://github.com/zendframework/zend-diactoros", + "keywords": [ + "http", + "psr", + "psr-7" + ], + "time": "2018-09-05T19:29:37+00:00" } ], "packages-dev": [ @@ -3604,16 +4327,16 @@ }, { "name": "laravel/dusk", - "version": "v4.0.3", + "version": "v4.0.4", "source": { "type": "git", "url": "https://github.com/laravel/dusk.git", - "reference": "94a2497d4a7ff3b4fc75acb55f9faeb50dcb4585" + "reference": "3b2df334d92b6215400ddd183253eb4bcc07debb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/dusk/zipball/94a2497d4a7ff3b4fc75acb55f9faeb50dcb4585", - "reference": "94a2497d4a7ff3b4fc75acb55f9faeb50dcb4585", + "url": "https://api.github.com/repos/laravel/dusk/zipball/3b2df334d92b6215400ddd183253eb4bcc07debb", + "reference": "3b2df334d92b6215400ddd183253eb4bcc07debb", "shasum": "" }, "require": { @@ -3661,20 +4384,20 @@ "testing", "webdriver" ], - "time": "2018-11-25T14:35:43+00:00" + "time": "2018-12-19T13:55:39+00:00" }, { "name": "laravel/telescope", - "version": "v1.0.7", + "version": "v1.0.10", "source": { "type": "git", "url": "https://github.com/laravel/telescope.git", - "reference": "807e2ed47ff14887ff2ceb9768e5ee208db88b52" + "reference": "4962a3c3a5da71756dd01dad2ea86e55fbb86df8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/telescope/zipball/807e2ed47ff14887ff2ceb9768e5ee208db88b52", - "reference": "807e2ed47ff14887ff2ceb9768e5ee208db88b52", + "url": "https://api.github.com/repos/laravel/telescope/zipball/4962a3c3a5da71756dd01dad2ea86e55fbb86df8", + "reference": "4962a3c3a5da71756dd01dad2ea86e55fbb86df8", "shasum": "" }, "require": { @@ -3724,7 +4447,7 @@ "laravel", "monitoring" ], - "time": "2018-11-28T15:33:53+00:00" + "time": "2018-12-09T16:34:14+00:00" }, { "name": "mikey179/vfsStream", @@ -4416,6 +5139,7 @@ "testing", "xunit" ], + "abandoned": true, "time": "2018-02-07T06:47:59+00:00" }, { @@ -4672,16 +5396,16 @@ }, { "name": "phpunit/phpunit", - "version": "7.4.4", + "version": "7.5.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "b1be2c8530c4c29c3519a052c9fb6cee55053bbd" + "reference": "c23d78776ad415d5506e0679723cb461d71f488f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/b1be2c8530c4c29c3519a052c9fb6cee55053bbd", - "reference": "b1be2c8530c4c29c3519a052c9fb6cee55053bbd", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c23d78776ad415d5506e0679723cb461d71f488f", + "reference": "c23d78776ad415d5506e0679723cb461d71f488f", "shasum": "" }, "require": { @@ -4702,7 +5426,7 @@ "phpunit/php-timer": "^2.0", "sebastian/comparator": "^3.0", "sebastian/diff": "^3.0", - "sebastian/environment": "^3.1 || ^4.0", + "sebastian/environment": "^4.0", "sebastian/exporter": "^3.1", "sebastian/global-state": "^2.0", "sebastian/object-enumerator": "^3.0.3", @@ -4726,7 +5450,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "7.4-dev" + "dev-master": "7.5-dev" } }, "autoload": { @@ -4752,7 +5476,7 @@ "testing", "xunit" ], - "time": "2018-11-14T16:52:02+00:00" + "time": "2018-12-12T07:20:32+00:00" }, { "name": "sebastian/code-unit-reverse-lookup", @@ -5319,7 +6043,7 @@ }, { "name": "symfony/filesystem", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", @@ -5369,7 +6093,7 @@ }, { "name": "symfony/options-resolver", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", @@ -5482,7 +6206,7 @@ }, { "name": "symfony/stopwatch", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", @@ -5532,7 +6256,7 @@ }, { "name": "symfony/yaml", - "version": "v4.2.0", + "version": "v4.2.1", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", diff --git a/database/migrations/2018_12_05_151224_adiciona_coluna_tipo_base_historico_disciplinas.php b/database/migrations/2018_12_05_151224_adiciona_coluna_tipo_base_historico_disciplinas.php new file mode 100644 index 0000000000..be2c762944 --- /dev/null +++ b/database/migrations/2018_12_05_151224_adiciona_coluna_tipo_base_historico_disciplinas.php @@ -0,0 +1,34 @@ +integer('tipo_base')->default(1); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('pmieducar.historico_disciplinas', function (Blueprint $table) { + /** @see ComponenteCurricular_Model_TipoBase::COMUM */ + $table->dropColumn('tipo_base'); + }); + } +} diff --git a/database/migrations/2018_12_06_161653_altera_tamanho_coluna_cartorio_na_tabela_historico_documento.php b/database/migrations/2018_12_06_161653_altera_tamanho_coluna_cartorio_na_tabela_historico_documento.php new file mode 100644 index 0000000000..04ced5f545 --- /dev/null +++ b/database/migrations/2018_12_06_161653_altera_tamanho_coluna_cartorio_na_tabela_historico_documento.php @@ -0,0 +1,32 @@ +string('cartorio_cert_civil')->change(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('historico.documento', function (Blueprint $table) { + $table->string('cartorio_cert_civil', 150)->change(); + }); + } +} diff --git a/docker/php/Dockerfile b/docker/php/Dockerfile index 4a95b429a9..48427466d2 100644 --- a/docker/php/Dockerfile +++ b/docker/php/Dockerfile @@ -47,3 +47,6 @@ RUN ln -s /application/artisan /usr/local/bin/artisan ENV COMPOSER_ALLOW_SUPERUSER 1 ENV COMPOSER_PROCESS_TIMEOUT 900 + +RUN mkdir -p /usr/share/man/man7 +RUN apt-get install -y postgresql-client diff --git a/ieducar/intranet/educar_calendario_ano_letivo_lst.php b/ieducar/intranet/educar_calendario_ano_letivo_lst.php index 22c5b5d3cf..13b28bd500 100644 --- a/ieducar/intranet/educar_calendario_ano_letivo_lst.php +++ b/ieducar/intranet/educar_calendario_ano_letivo_lst.php @@ -1,529 +1,501 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Prefeitura Municipal de Itajaí - * @category i-Educar - * @license @@license@@ - * @package iEd_Pmieducar - * @since Arquivo disponível desde a versão 1.0.0 - * @version $Id$ - */ - require_once 'include/clsBase.inc.php'; require_once 'include/clsListagem.inc.php'; require_once 'include/clsBanco.inc.php'; require_once 'include/pmieducar/geral.inc.php'; require_once 'clsCalendario.inc.php'; - require_once 'Calendario/Model/TurmaDataMapper.php'; require_once 'App/Model/IedFinder.php'; require_once 'include/localizacaoSistema.php'; require_once 'include/pmieducar/clsPmieducarEscolaUsuario.inc.php'; -/** - * clsIndexBase class. - * - * @author Prefeitura Municipal de Itajaí - * @category i-Educar - * @license @@license@@ - * @package iEd_Pmieducar - * @since Classe disponível desde a versão 1.0.0 - * @version @@package_version@@ - */ class clsIndexBase extends clsBase { - function Formular() - { - $this->SetTitulo($this->_instituicao . ' i-Educar - Calendários'); - $this->addScript('calendario'); - $this->processoAp = 620; - $this->addEstilo("localizacaoSistema"); - } + function Formular() + { + $this->SetTitulo($this->_instituicao . ' i-Educar - Calendários'); + $this->addScript('calendario'); + $this->processoAp = 620; + $this->addEstilo("localizacaoSistema"); + } } -/** - * indice class. - * - * @author Prefeitura Municipal de Itajaí - * @category i-Educar - * @license @@license@@ - * @package iEd_Pmieducar - * @since Classe disponível desde a versão 1.0.0 - * @version @@package_version@@ - */ -class indice extends clsConfig +class indice extends clsListagem { - var $pessoa_logada; - var $titulo; - var $limite; - var $offset; - - var $cod_calendario_ano_letivo; - var $ref_cod_escola; - var $ref_usuario_exc; - var $ref_usuario_cad; - var $data_cadastra; - var $data_exclusao; - var $ativo; - var $inicio_ano_letivo; - var $termino_ano_letivo; - - var $ref_cod_instituicao; - var $ano; - var $mes; + var $pessoa_logada; + var $titulo; + var $limite; + var $offset; + var $cod_calendario_ano_letivo; + var $ref_cod_escola; + var $ref_usuario_exc; + var $ref_usuario_cad; + var $data_cadastra; + var $data_exclusao; + var $ativo; + var $inicio_ano_letivo; + var $termino_ano_letivo; + var $ref_cod_instituicao; + var $ano; + var $mes; function renderHTML() { - @session_start(); + @session_start(); + $this->pessoa_logada = $_SESSION['id_pessoa']; + session_write_close(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - $_SESSION['calendario']['ultimo_valido'] = 0; + $obj_permissoes = new clsPermissoes(); - $obj_permissoes = new clsPermissoes(); + $nivel = $obj_permissoes->nivel_acesso($this->pessoa_logada); - if ($obj_permissoes->nivel_acesso($this->pessoa_logada) > 7) { - $retorno .= ' - - '; - - $retorno .= ' - - - '; - - $retorno .= ' - -
-
Usuário sem permissão para acessar esta página
-
'; - - return $retorno; - } + $retorno = null; - $retorno .= ' - - '; + if ($nivel > 7) { + $retorno = ' +
+ + + + + +
+
Usuário sem permissão para acessar esta página
+
'; - $localizacao = new LocalizacaoSistema(); - $localizacao->entradaCaminhos( array( - $_SERVER['SERVER_NAME']."/intranet" => "Início", - "educar_index.php" => "Escola", - "" => "Calendários" - )); - $this->locale = $localizacao->montar(); - - if ($this->locale){ + return $retorno; + } - $retorno .= " - {$this->locale} - "; - } + $retorno = ''; - if ($_POST) { - $this->ref_cod_escola = $_POST['ref_cod_escola'] ? - $_POST['ref_cod_escola'] : $_SESSION['calendario']['ref_cod_escola']; + $localizacao = new LocalizacaoSistema(); + $localizacao->entradaCaminhos( + [ + $_SERVER['SERVER_NAME'] . "/intranet" => "Início", + "educar_index.php" => "Escola", + "" => "Calendários" + ] + ); - $this->ref_cod_instituicao = $_POST['ref_cod_instituicao'] ? - $_POST['ref_cod_instituicao'] : $_SESSION['calendario']['ref_cod_instituicao']; + $this->locale = $localizacao->montar(); - if ($_POST['mes']) { - $this->mes = $_POST['mes']; + if ($this->locale) { + $retorno .= " + + + "; } - if ($_POST['ano']) { - $this->ano = $_POST['ano']; + if ($_POST) { + $this->ref_cod_escola = $_POST['ref_cod_escola'] ? $_POST['ref_cod_escola'] : $_SESSION['calendario']['ref_cod_escola']; + $this->ref_cod_instituicao = $_POST['ref_cod_instituicao'] ? $_POST['ref_cod_instituicao'] : $_SESSION['calendario']['ref_cod_instituicao']; + if ($_POST['mes']) { + $this->mes = $_POST['mes']; + } + if ($_POST['ano']) { + $this->ano = $_POST['ano']; + } + if ($_POST['cod_calendario_ano_letivo']) { + $this->cod_calendario_ano_letivo = $_POST['cod_calendario_ano_letivo']; + } + } elseif (isset($_SESSION['calendario'])) { + // passa todos os valores em SESSION para atributos do objeto + foreach ($_SESSION['calendario'] as $var => $val) { + $this->$var = ($val === '') ? null : $val; + } } - if ($_POST['cod_calendario_ano_letivo']) { - $this->cod_calendario_ano_letivo = $_POST['cod_calendario_ano_letivo']; - } - } - elseif (isset($_SESSION['calendario'])) { - // passa todos os valores em SESSION para atributos do objeto - foreach ($_SESSION['calendario'] as $var => $val) { - $this->$var = ($val === '') ? NULL : $val; + if ($_GET) { + header('Location: educar_calendario_ano_letivo_lst.php'); } - } - - if ($_GET) { - header('Location: educar_calendario_ano_letivo_lst.php'); - } - - if (!$this->mes) { - $this->mes = date('n'); - } - - if (!$this->ano) { - $this->ano = date('Y'); - } - $nivel_usuario = $obj_permissoes->nivel_acesso($this->pessoa_logada); - - if (! $this->ref_cod_escola) { - $this->ref_cod_escola = $obj_permissoes->getEscola($this->pessoa_logada); - } - - if (! $this->ref_cod_instituicao) { - $this->ref_cod_instituicao = $obj_permissoes->getInstituicao($this->pessoa_logada); - } - - $get_escola = 1; - $obrigatorio = FALSE; - - include 'educar_calendario_pesquisas.php'; - - $obj_calendario_ano_letivo = new clsPmieducarCalendarioAnoLetivo(); - $obj_calendario_ano_letivo->setOrderby('ano ASC'); - $obj_calendario_ano_letivo->setLimite($this->limite, $this->offset); - - $lista = array(); - $obj_calendario_ano_letivo->setOrderby('ano'); - - switch ($nivel_usuario) { - // Poli-institucional - case 1: - case 2: - case 4: - if (!isset($this->ref_cod_escola)) { - break; - } - - $lista = $obj_calendario_ano_letivo->lista( - $this->cod_calendario_ano_letivo, - $this->ref_cod_escola, - NULL, - NULL, - (!isset($this->cod_calendario_ano_letivo) ? $this->ano : NULL), - NULL, - NULL, - 1 - ); - break; - } + if (!$this->mes) { + $this->mes = date('n'); + } - $total = $obj_calendario_ano_letivo->_total; + if (!$this->ano) { + $this->ano = date('Y'); + } - if (empty($lista)) { - if ($nivel_usuario == 4) { - $retorno .= ''; + if (!$this->ref_cod_escola) { + $this->ref_cod_escola = $obj_permissoes->getEscola($this->pessoa_logada); } - else { - if ($_POST) { - $retorno .= ''; - } - else { - $retorno .= ''; - } + + if (!$this->ref_cod_instituicao) { + $this->ref_cod_instituicao = $obj_permissoes->getInstituicao($this->pessoa_logada); } - } - // Monta a lista - if (is_array($lista) && count($lista)) { - foreach ($lista as $key => $registro) { - // Guarda dados na $_SESSION - $_SESSION['calendario'] = array( - 'cod_calendario_ano_letivo' => $registro['cod_calendario_ano_letivo'], - 'ref_cod_instituicao' => $this->ref_cod_instituicao, - 'ref_cod_escola' => $this->ref_cod_escola, - 'ano' => $this->ano, - 'mes' => $this->mes - ); - - // Nome da escola - $obj_ref_cod_escola = new clsPmieducarEscola($registro['ref_cod_escola']); - $det_ref_cod_escola = $obj_ref_cod_escola->detalhe(); - $registro['nm_escola'] = $det_ref_cod_escola['nome']; - - // Início e término do ano letivo. - $obj_ano_letivo_modulo = new clsPmieducarAnoLetivoModulo(); - - $inicio_ano = $obj_ano_letivo_modulo->menorData( - $registro['ano'], $this->ref_cod_escola - ); - - $fim_ano = $obj_ano_letivo_modulo->maiorData( - $registro['ano'], $this->ref_cod_escola - ); - - $inicio_ano = explode('/', dataFromPgToBr($inicio_ano)); - $fim_ano = explode('/', dataFromPgToBr($fim_ano)); - - // Turmas da escola - $turmas = App_Model_IedFinder::getTurmas($registro['ref_cod_escola']); - - // Mapper de Calendario_Model_TurmaDataMapper - $calendarioTurmaMapper = new Calendario_Model_TurmaDataMapper(); - - $obj_calendario = new clsCalendario(); - $obj_calendario->setLargura(600); - $obj_calendario->permite_trocar_ano = TRUE; - - $obj_calendario->setCorDiaSemana(array(0, 6), 'ROSA'); - - $obj_dia_calendario = new clsPmieducarCalendarioDia( - $registro['cod_calendario_ano_letivo'], $this->mes, NULL, NULL, NULL, - NULL, NULL - ); - - $lista_dia = $obj_dia_calendario->lista( - $registro['cod_calendario_ano_letivo'], $this->mes, NULL, NULL, NULL, NULL - ); - - if ($lista_dia) { - $array_dias = array(); - $array_descricao = array(); - - foreach ($lista_dia as $dia) { - $descricao = ''; - - $url = sprintf( - 'educar_calendario_anotacao_lst.php?ref_cod_calendario_ano_letivo=%s&ref_cod_escola=%s&dia=%s&mes=%s&ano=%s', - $registro['cod_calendario_ano_letivo'], $this->ref_cod_escola, - $dia['dia'], $dia['mes'], $this->ano - ); - - $botao_editar = sprintf(' -
-
- -
', $url); - - if ($dia['ref_cod_calendario_dia_motivo']) { - $array_dias[$dia['dia']] = $dia['dia']; - - $obj_motivo = new clsPmieducarCalendarioDiaMotivo($dia['ref_cod_calendario_dia_motivo']); - $det_motivo = $obj_motivo->detalhe(); - - /** - * @todo CoreExt_Enum? - */ - $tipo = strtoupper($det_motivo['tipo']) == 'E' ? - 'Dia Extra-Letivo' : 'Dia Não Letivo'; - - // Busca pelas turmas que estão marcadas para esse dia - $args = array( - 'calendarioAnoLetivo' => $registro['cod_calendario_ano_letivo'], - 'mes' => $dia['mes'], - 'dia' => $dia['dia'], - 'ano' => $this->ano - ); + $get_escola = 1; + $obrigatorio = FALSE; + include 'educar_calendario_pesquisas.php'; - $calendarioTurmas = $calendarioTurmaMapper->findAll(array(), $args); + $obj_calendario_ano_letivo = new clsPmieducarCalendarioAnoLetivo(); + $obj_calendario_ano_letivo->setOrderby('ano ASC'); + $obj_calendario_ano_letivo->setLimite($this->limite, $this->offset); - $nomeTurmas = array(); - foreach ($calendarioTurmas as $calendarioTurma) { - $nomeTurmas[] = $turmas[$calendarioTurma->turma]; - } + $lista = []; + $obj_calendario_ano_letivo->setOrderby('ano'); - if (0 == count($nomeTurmas)) { - $calendarioTurmas = ''; - } - else { - $calendarioTurmas = 'Turmas: '; + switch ($nivel) { + // Poli-institucional + case 1: + case 2: + case 4: + if (!isset($this->ref_cod_escola)) { + break; } - $descricao = sprintf( - '
%s
Motivo: %s
Descrição: %s
%s
%s', - $tipo, $det_motivo['nm_motivo'], $dia['descricao'], $calendarioTurmas, $botao_editar + $lista = $obj_calendario_ano_letivo->lista( + $this->cod_calendario_ano_letivo, + $this->ref_cod_escola, + null, + null, + (!isset($this->cod_calendario_ano_letivo) ? $this->ano : null), + null, + null, + 1 ); + break; + } - $array_descricao[$dia['dia']] = $descricao; - - if (strtoupper($det_motivo['tipo']) == 'E') { - $obj_calendario->adicionarLegenda('Extra Letivo', 'LARANJA_ESCURO'); - $obj_calendario->adicionarArrayDias('Extra Letivo', array($dia['dia'])); - } - elseif (strtoupper($det_motivo['tipo']) == 'N') { - $obj_calendario->adicionarLegenda('Não Letivo', '#VERDE_ESCURO'); - $obj_calendario->adicionarArrayDias('Não Letivo', array($dia['dia'])); + $total = $obj_calendario_ano_letivo->_total; + + if (empty($lista)) { + if ($nivel == 4) { + $retorno .= ' + + + '; + } else { + if ($_POST) { + $retorno .= ' + + + '; + } else { + $retorno .= ' + + + '; } + } + } - $obj_calendario->diaDescricao($array_dias, $array_descricao); - } - elseif ($dia['descricao']) { - $array_dias[$dia['dia']] = $dia['dia']; + // Monta a lista + if (is_array($lista) && count($lista)) { + foreach ($lista as $key => $registro) { + // Guarda dados na $_SESSION + $_SESSION['calendario'] = [ + 'cod_calendario_ano_letivo' => $registro['cod_calendario_ano_letivo'], + 'ref_cod_instituicao' => $this->ref_cod_instituicao, + 'ref_cod_escola' => $this->ref_cod_escola, + 'ano' => $this->ano, + 'mes' => $this->mes + ]; + + // Nome da escola + $obj_ref_cod_escola = new clsPmieducarEscola($registro['ref_cod_escola']); + $det_ref_cod_escola = $obj_ref_cod_escola->detalhe(); + $registro['nm_escola'] = $det_ref_cod_escola['nome']; + + // Início e término do ano letivo. + $obj_ano_letivo_modulo = new clsPmieducarAnoLetivoModulo(); + + $inicio_ano = $obj_ano_letivo_modulo->menorData( + $registro['ano'], $this->ref_cod_escola + ); - $descricao = sprintf( - '
Descrição: %s
%s', - $dia['descricao'], $botao_editar + $fim_ano = $obj_ano_letivo_modulo->maiorData( + $registro['ano'], $this->ref_cod_escola ); - $array_descricao[$dia['dia']] = $descricao; - } - } + $inicio_ano = explode('/', dataFromPgToBr($inicio_ano)); + $fim_ano = explode('/', dataFromPgToBr($fim_ano)); - if (! empty($array_dias)) { - $obj_calendario->diaDescricao($array_dias, $array_descricao); - } - } + // Turmas da escola + $turmas = App_Model_IedFinder::getTurmas($registro['ref_cod_escola']); - if ($this->mes <= (int) $inicio_ano[1] && $this->ano == (int) $inicio_ano[2]) { - if ($this->mes == (int) $inicio_ano[1]) { - $obj_calendario->adicionarLegenda('Início Ano Letivo', 'AMARELO'); - $obj_calendario->adicionarArrayDias('Início Ano Letivo', array($inicio_ano[0])); - } + // Mapper de Calendario_Model_TurmaDataMapper + $calendarioTurmaMapper = new Calendario_Model_TurmaDataMapper(); - $dia_inicio = (int) $inicio_ano[0]; - $dias = array(); + $obj_calendario = new clsCalendario(); + $obj_calendario->setLargura(600); + $obj_calendario->permite_trocar_ano = true; - if ($this->mes < (int) $inicio_ano[1]) { - $NumeroDiasMes = (int) date('t', $this->mes); + $obj_calendario->setCorDiaSemana([0, 6], 'ROSA'); - for ($d = 1 ; $d <= $NumeroDiasMes; $d++) { - $dias[] = $d; - } + $obj_dia_calendario = new clsPmieducarCalendarioDia( + $registro['cod_calendario_ano_letivo'], $this->mes, null, null, null, null, null + ); - $obj_calendario->setLegendaPadrao('Não Letivo'); + $lista_dia = $obj_dia_calendario->lista( + $registro['cod_calendario_ano_letivo'], $this->mes, null, null, null, null + ); - if (!empty($dias)){ - $obj_calendario->adicionarArrayDias('Não Letivo', $dias); - } - } - else { - $dia_inicio; - - for ($d = 1 ; $d < $dia_inicio ; $d++) { - $dias[] = $d; - } - - $obj_calendario->setLegendaPadrao('Dias Letivos', 'AZUL_CLARO'); - if (! empty($dias)){ - $obj_calendario->adicionarLegenda('Não Letivo', '#F7F7F7'); - $obj_calendario->adicionarArrayDias('Não Letivo', $dias); - } - } - } - elseif ($this->mes >= (int)$fim_ano[1] && $this->ano == (int)$fim_ano[2] ){ - $dia_inicio = (int)$fim_ano[0]; - $dias = array(); + if ($lista_dia) { + $array_dias = []; + $array_descricao = []; + + foreach ($lista_dia as $dia) { + $url = sprintf( + 'educar_calendario_anotacao_lst.php?ref_cod_calendario_ano_letivo=%s&ref_cod_escola=%s&dia=%s&mes=%s&ano=%s', + $registro['cod_calendario_ano_letivo'], + $this->ref_cod_escola, + $dia['dia'], + $dia['mes'], + $this->ano + ); + + $botao_editar = sprintf(' +

+ +
', + $url + ); + + if ($dia['ref_cod_calendario_dia_motivo']) { + $array_dias[$dia['dia']] = $dia['dia']; + + $obj_motivo = new clsPmieducarCalendarioDiaMotivo($dia['ref_cod_calendario_dia_motivo']); + $det_motivo = $obj_motivo->detalhe(); + + /** + * @todo CoreExt_Enum? + */ + $tipo = strtoupper($det_motivo['tipo']) == 'E' ? 'Dia Extra-Letivo' : 'Dia Não Letivo'; + + // Busca pelas turmas que estão marcadas para esse dia + $args = [ + 'calendarioAnoLetivo' => $registro['cod_calendario_ano_letivo'], + 'mes' => $dia['mes'], + 'dia' => $dia['dia'], + 'ano' => $this->ano + ]; + + $calendarioTurmas = $calendarioTurmaMapper->findAll([], $args); + + $nomeTurmas = []; + foreach ($calendarioTurmas as $calendarioTurma) { + $nomeTurmas[] = $turmas[$calendarioTurma->turma]; + } + + if (0 == count($nomeTurmas)) { + $calendarioTurmas = ''; + } else { + $calendarioTurmas = 'Turmas: '; + } + + $descricao = sprintf( + '
+ %s +
+
+ Motivo: %s
+ Descrição: %s
%s +
%s', + $tipo, + $det_motivo['nm_motivo'], + $dia['descricao'], + $calendarioTurmas, + $botao_editar + ); + + $array_descricao[$dia['dia']] = $descricao; + + if (strtoupper($det_motivo['tipo']) == 'E') { + $obj_calendario->adicionarLegenda('Extra Letivo', 'LARANJA_ESCURO'); + $obj_calendario->adicionarArrayDias('Extra Letivo', [$dia['dia']]); + } elseif (strtoupper($det_motivo['tipo']) == 'N') { + $obj_calendario->adicionarLegenda('Não Letivo', '#VERDE_ESCURO'); + $obj_calendario->adicionarArrayDias('Não Letivo', [$dia['dia']]); + } + + $obj_calendario->diaDescricao($array_dias, $array_descricao); + + } elseif ($dia['descricao']) { + $array_dias[$dia['dia']] = $dia['dia']; + $descricao = sprintf( + '
+ Descrição: %s +
%s', + $dia['descricao'], + $botao_editar + ); + $array_descricao[$dia['dia']] = $descricao; + } + } + + if (!empty($array_dias)) { + $obj_calendario->diaDescricao($array_dias, $array_descricao); + } + } - if ($this->mes > (int)$fim_ano[1]) { - $NumeroDiasMes = (int) date('t',$this->mes); + if ($this->mes <= (int)$inicio_ano[1] && $this->ano == (int)$inicio_ano[2]) { + if ($this->mes == (int)$inicio_ano[1]) { + $obj_calendario->adicionarLegenda('Início Ano Letivo', 'AMARELO'); + $obj_calendario->adicionarArrayDias('Início Ano Letivo', [$inicio_ano[0]]); + } + + $dia_inicio = (int)$inicio_ano[0]; + $dias = []; + + if ($this->mes < (int)$inicio_ano[1]) { + $NumeroDiasMes = (int)date('t', $this->mes); + + for ($d = 1; $d <= $NumeroDiasMes; $d++) { + $dias[] = $d; + } + + $obj_calendario->setLegendaPadrao('Não Letivo'); + + if (!empty($dias)) { + $obj_calendario->adicionarArrayDias('Não Letivo', $dias); + } + } else { + $dia_inicio; + + for ($d = 1; $d < $dia_inicio; $d++) { + $dias[] = $d; + } + + $obj_calendario->setLegendaPadrao('Dias Letivos', 'AZUL_CLARO'); + if (!empty($dias)) { + $obj_calendario->adicionarLegenda('Não Letivo', '#F7F7F7'); + $obj_calendario->adicionarArrayDias('Não Letivo', $dias); + } + } + } elseif ($this->mes >= (int)$fim_ano[1] && $this->ano == (int)$fim_ano[2]) { + $dia_inicio = (int)$fim_ano[0]; + $dias = []; + + if ($this->mes > (int)$fim_ano[1]) { + $NumeroDiasMes = (int)date('t', $this->mes); + + for ($d = 1; $d <= $NumeroDiasMes; $d++) { + $dias[] = $d; + } + + $obj_calendario->setLegendaPadrao('Não Letivo'); + + if (!empty($dias)) { + $obj_calendario->adicionarArrayDias('Não Letivo', $dias); + } + } else { + $NumeroDiasMes = (int)date('t', $this->mes); + + for ($d = $fim_ano[0]; $d <= $NumeroDiasMes; $d++) { + $dias[] = $d; + } + + $obj_calendario->setLegendaPadrao('Dias Letivos', 'AZUL_CLARO'); + + if (!empty($dias)) { + $obj_calendario->adicionarLegenda('Não Letivo', '#F7F7F7'); + $obj_calendario->adicionarArrayDias('Não Letivo', $dias); + } + } + + if ($this->mes == (int)$fim_ano[1]) { + $obj_calendario->adicionarLegenda('Término Ano Letivo', 'AMARELO'); + $obj_calendario->adicionarArrayDias('Término Ano Letivo', [$fim_ano[0]]); + } + } else { + $obj_calendario->setLegendaPadrao('Dias Letivos', 'AZUL_CLARO'); + } - for ($d = 1 ; $d <= $NumeroDiasMes; $d++) { - $dias[] = $d; - } + $obj_calendario->setCorDiaSemana([0, 6], 'ROSA'); - $obj_calendario->setLegendaPadrao('Não Letivo'); + $obj_anotacao = new clsPmieducarCalendarioDiaAnotacao(); + $lista_anotacoes = $obj_anotacao->lista( + null, + $this->mes, + $registro['cod_calendario_ano_letivo'], + null, + 1 + ); - if (! empty($dias)) { - $obj_calendario->adicionarArrayDias('Não Letivo', $dias); - } - } - else { - $NumeroDiasMes = (int) date('t', $this->mes); + if ($lista_anotacoes) { + $dia_anotacao = []; + foreach ($lista_anotacoes as $anotacao) { + if ($this->mes == (int)$anotacao['ref_mes']) { + $dia_anotacao[$anotacao['ref_dia']] = $anotacao['ref_dia']; + } + } - for ($d = $fim_ano[0] ; $d <= $NumeroDiasMes; $d++) { - $dias[] = $d; - } + $obj_calendario->adicionarIconeDias($dia_anotacao, 'A'); + } - $obj_calendario->setLegendaPadrao('Dias Letivos', 'AZUL_CLARO'); + $obj_calendario->all_days_url = sprintf( + 'educar_calendario_anotacao_lst.php?ref_cod_calendario_ano_letivo=%s', + $registro['cod_calendario_ano_letivo'] + ); - if (! empty($dias)) { - $obj_calendario->adicionarLegenda('Não Letivo', '#F7F7F7'); - $obj_calendario->adicionarArrayDias('Não Letivo', $dias); - } - } + // Gera código HTML do calendário + $calendario = $obj_calendario->getCalendario( + $this->mes, + $this->ano, + 'mes_corrente', + $_GET, + ['cod_calendario_ano_letivo' => $registro['cod_calendario_ano_letivo']] + ); - if ($this->mes == (int) $fim_ano[1]) { - $obj_calendario->adicionarLegenda('Término Ano Letivo', 'AMARELO'); - $obj_calendario->adicionarArrayDias('Término Ano Letivo', array($fim_ano[0])); - } - } - else { - $obj_calendario->setLegendaPadrao('Dias Letivos', 'AZUL_CLARO'); - } - - $obj_calendario->setCorDiaSemana(array(0, 6), 'ROSA'); - - $obj_anotacao = new clsPmieducarCalendarioDiaAnotacao(); - $lista_anotacoes = $obj_anotacao->lista( - NULL, $this->mes, $registro['cod_calendario_ano_letivo'], NULL, 1 - ); - - if ($lista_anotacoes) { - $dia_anotacao = array(); - foreach ($lista_anotacoes as $anotacao) { - if ($this->mes == (int) $anotacao['ref_mes']) { - $dia_anotacao[$anotacao['ref_dia']] = $anotacao['ref_dia']; - } + $retorno .= sprintf(' + + + ', + $registro['nm_escola'], + $calendario + ); } - - $obj_calendario->adicionarIconeDias($dia_anotacao, 'A'); - } - - $obj_calendario->all_days_url = sprintf( - 'educar_calendario_anotacao_lst.php?ref_cod_calendario_ano_letivo=%s', - $registro['cod_calendario_ano_letivo'] - ); - - // Gera código HTML do calendário - $calendario = $obj_calendario->getCalendario( - $this->mes, $this->ano, 'mes_corrente', $_GET, - array('cod_calendario_ano_letivo' => $registro['cod_calendario_ano_letivo']) - ); - - $retorno .= sprintf( - '', - $registro['nm_escola'], $calendario - ); } - } - if ($obj_permissoes->permissao_cadastra(620, $this->pessoa_logada, 7)) { - if ($_POST && empty($lista) && $_SESSION['calendario']['ultimo_valido']) { - $url = sprintf( - 'educar_calendario_ano_letivo_lst.php?ref_cod_instituicao=%s&ref_cod_escola=%s&ano=%s', - $this->ref_cod_instituicao, $this->ref_cod_escola, $_SESSION['calendario']['ano'] - ); - - $bt_voltar = sprintf( - '', - $url - ); - } + if ($obj_permissoes->permissao_cadastra(620, $this->pessoa_logada, 7)) { + if ($_POST && empty($lista) && $_SESSION['calendario']['ultimo_valido']) { + $url = sprintf( + 'educar_calendario_ano_letivo_lst.php?ref_cod_instituicao=%s&ref_cod_escola=%s&ano=%s', + $this->ref_cod_instituicao, + $this->ref_cod_escola, + $_SESSION['calendario']['ano'] + ); - $url = sprintf( - 'educar_calendario_ano_letivo_cad.php?ref_cod_instituicao=%s&ref_cod_escola=%s', - $this->ref_cod_instituicao, $this->ref_cod_escola - ); + $bt_voltar = sprintf( + '', + $url + ); + } - $retorno .= sprintf(' - - - - - - ', $bt_voltar, $url); - } + $url = sprintf( + 'educar_calendario_ano_letivo_cad.php?ref_cod_instituicao=%s&ref_cod_escola=%s', + $this->ref_cod_instituicao, + $this->ref_cod_escola + ); + + $retorno .= sprintf(' + + + + + + ', + $bt_voltar, + $url + ); + } - $retorno .=' - -
+ {$this->locale} +
Sem Calendário Letivo
Sem Calendário para o ano selecionado
Selecione uma escola para exibir o calendário
Sem Calendário Letivo
Sem Calendário para o ano selecionado
Selecione uma escola para exibir o calendário
+
+ + %s + %s +
+
%s%s
 
- %s - -
 
+ %s +
'; + $retorno .= ' '; - return $retorno; + return $retorno; } } diff --git a/ieducar/intranet/educar_calendario_pesquisas.php b/ieducar/intranet/educar_calendario_pesquisas.php index d36c97aa8c..9f7b53d26c 100644 --- a/ieducar/intranet/educar_calendario_pesquisas.php +++ b/ieducar/intranet/educar_calendario_pesquisas.php @@ -52,14 +52,14 @@ } } } else { - $opcoes = array('' => 'Erro na geração'); + $opcoes = array('' => 'Erro na geração'); } if ($get_escola) { $retorno .= ' - Instituição + Instituição *
'; @@ -154,7 +154,7 @@ } } } else { - $opcoes_escola = array('' => 'Erro na geração'); + $opcoes_escola = array('' => 'Erro na geração'); } } @@ -199,7 +199,7 @@ } if ($nivel_usuario == 1) { - ${$get_cabecalho}[] = 'Instituição'; + ${$get_cabecalho}[] = 'Instituição'; } } @@ -302,7 +302,7 @@ function getEscola() if (campoEscola.length == 1 && campoInstituicao != '') { campoEscola.options[0] = new Option( - 'A institução não possui nenhuma escola', '', false, false + 'A institução não possui nenhuma escola', '', false, false ); } diff --git a/ieducar/intranet/educar_curso_cad.php b/ieducar/intranet/educar_curso_cad.php index 8c41a53705..f354c7b547 100644 --- a/ieducar/intranet/educar_curso_cad.php +++ b/ieducar/intranet/educar_curso_cad.php @@ -1,36 +1,5 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Prefeitura Municipal de Itajaí - * @category i-Educar - * @license @@license@@ - * @package iEd_Pmieducar - * @since Arquivo disponível desde a versão 1.0.0 - * @version $Id$ - */ - require_once 'include/clsBase.inc.php'; require_once 'include/clsCadastro.inc.php'; require_once 'include/clsBanco.inc.php'; @@ -39,518 +8,688 @@ require_once 'Portabilis/View/Helper/Application.php'; require_once 'include/modules/clsModulesAuditoriaGeral.inc.php'; -/** - * clsIndexBase class. - * - * @author Prefeitura Municipal de Itajaí - * @category i-Educar - * @license @@license@@ - * @package iEd_Pmieducar - * @since Classe disponível desde a versão 1.0.0 - * @version @@package_version@@ - */ class clsIndexBase extends clsBase { - function Formular() - { - $this->SetTitulo($this->_instituicao . ' i-Educar - Curso'); - $this->processoAp = '566'; - $this->addEstilo("localizacaoSistema"); - } + public function Formular() + { + $this->SetTitulo($this->_instituicao . ' i-Educar - Curso'); + $this->processoAp = '566'; + $this->addEstilo('localizacaoSistema'); + } } -/** - * indice class. - * - * @author Prefeitura Municipal de Itajaí - * @category i-Educar - * @license @@license@@ - * @package iEd_Pmieducar - * @since Classe disponível desde a versão 1.0.0 - * @version @@package_version@@ - */ class indice extends clsCadastro { - var $pessoa_logada; - - var $cod_curso; - var $ref_usuario_cad; - var $ref_cod_tipo_regime; - var $ref_cod_nivel_ensino; - var $ref_cod_tipo_ensino; - var $nm_curso; - var $sgl_curso; - var $qtd_etapas; - var $carga_horaria; - var $ato_poder_publico; - var $habilitacao; - var $objetivo_curso; - var $publico_alvo; - var $data_cadastro; - var $data_exclusao; - var $ativo; - var $ref_usuario_exc; - var $ref_cod_instituicao; - var $padrao_ano_escolar; - var $hora_falta; - - var $incluir; - var $excluir_; - var $habilitacao_curso; - var $curso_sem_avaliacao = true; - - var $multi_seriado; - var $modalidade_curso; - - function Inicializar() - { - $retorno = 'Novo'; - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - - $this->cod_curso = $_GET['cod_curso']; - - $obj_permissoes = new clsPermissoes(); - $obj_permissoes->permissao_cadastra(566, $this->pessoa_logada, 3, - 'educar_curso_lst.php'); - - if (is_numeric($this->cod_curso)) { - $obj = new clsPmieducarCurso( $this->cod_curso ); - $registro = $obj->detalhe(); - - if ($registro) { - // passa todos os valores obtidos no registro para atributos do objeto - foreach($registro as $campo => $val) { - $this->$campo = $val; + public $pessoa_logada; + + public $cod_curso; + public $ref_usuario_cad; + public $ref_cod_tipo_regime; + public $ref_cod_nivel_ensino; + public $ref_cod_tipo_ensino; + public $nm_curso; + public $sgl_curso; + public $qtd_etapas; + public $carga_horaria; + public $ato_poder_publico; + public $habilitacao; + public $objetivo_curso; + public $publico_alvo; + public $data_cadastro; + public $data_exclusao; + public $ativo; + public $ref_usuario_exc; + public $ref_cod_instituicao; + public $padrao_ano_escolar; + public $hora_falta; + + public $incluir; + public $excluir_; + public $habilitacao_curso; + public $curso_sem_avaliacao = true; + + public $multi_seriado; + public $modalidade_curso; + + public function Inicializar() + { + $retorno = 'Novo'; + + $this->cod_curso = $this->getQueryString('cod_curso'); + + $obj_permissoes = new clsPermissoes(); + $obj_permissoes->permissao_cadastra( + 566, + $this->pessoa_logada, + 3, + 'educar_curso_lst.php' + ); + + if (is_numeric($this->cod_curso)) { + $obj = new clsPmieducarCurso($this->cod_curso); + $registro = $obj->detalhe(); + + if ($registro) { + // passa todos os valores obtidos no registro para atributos do objeto + foreach ($registro as $campo => $val) { + $this->$campo = $val; + } + + $this->fexcluir = $obj_permissoes->permissao_excluir( + 566, + $this->pessoa_logada, + 3 + ); + + $retorno = 'Editar'; + } } + $this->url_cancelar = ($retorno == 'Editar') ? + "educar_curso_det.php?cod_curso={$registro['cod_curso']}" : 'educar_curso_lst.php'; - $this->fexcluir = $obj_permissoes->permissao_excluir(566, - $this->pessoa_logada, 3); - - $retorno = 'Editar'; - } - } - $this->url_cancelar = ($retorno == 'Editar') ? - "educar_curso_det.php?cod_curso={$registro["cod_curso"]}" : 'educar_curso_lst.php'; - - $nomeMenu = $retorno == "Editar" ? $retorno : "Cadastrar"; - $localizacao = new LocalizacaoSistema(); - $localizacao->entradaCaminhos( array( - $_SERVER['SERVER_NAME']."/intranet" => "Início", - "educar_index.php" => "Escola", - "" => "{$nomeMenu} curso" - )); - $this->enviaLocalizacao($localizacao->montar()); - - $this->nome_url_cancelar = 'Cancelar'; - return $retorno; - } + $this->breadcrumb('Cursos', ['educar_index.php' => 'Escola']); - function Gerar() - { - if ($_POST) { - foreach ($_POST as $campo => $val) { - $this->$campo = ($this->$campo) ? $this->$campo : $val; - } - } + $this->nome_url_cancelar = 'Cancelar'; - if ($_POST['habilitacao_curso']) { - $this->habilitacao_curso = unserialize(urldecode($_POST['habilitacao_curso'])); + return $retorno; } - $qtd_habilitacao = (count($this->habilitacao_curso) == 0) ? - 1 : (count($this->habilitacao_curso) + 1); - - if (is_numeric($this->cod_curso) && $_POST['incluir'] != 'S' && - empty($_POST['excluir_'])) { - - $obj = new clsPmieducarHabilitacaoCurso(NULL, $this->cod_curso); - $registros = $obj->lista(NULL, $this->cod_curso); - - if ($registros) { - foreach ($registros as $campo) { - $this->habilitacao_curso[$campo[$qtd_habilitacao]]['ref_cod_habilitacao_'] = - $campo['ref_cod_habilitacao']; - - $qtd_habilitacao++; + public function Gerar() + { + if ($_POST) { + foreach ($_POST as $campo => $val) { + $this->$campo = ($this->$campo) ? $this->$campo : $val; + } } - } - } - - if ($_POST['habilitacao']) { - $this->habilitacao_curso[$qtd_habilitacao]['ref_cod_habilitacao_'] = - $_POST['habilitacao']; - - $qtd_habilitacao++; - unset($this->habilitacao); - } - - // primary keys - $this->campoOculto('cod_curso', $this->cod_curso); - - $obrigatorio = true; - include('include/pmieducar/educar_campo_lista.php'); - // Nível ensino - $opcoes = array( '' => 'Selecione' ); - - if ($this->ref_cod_instituicao) { - $objTemp = new clsPmieducarNivelEnsino(); - $lista = $objTemp->lista(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL,1,$this->ref_cod_instituicao); - - if (is_array($lista) && count($lista)) { - foreach ($lista as $registro) { - $opcoes[$registro['cod_nivel_ensino']] = $registro['nm_nivel']; + if ($_POST['habilitacao_curso']) { + $this->habilitacao_curso = unserialize(urldecode($_POST['habilitacao_curso'])); } - } - } - $script = "javascript:showExpansivelIframe(520, 230, 'educar_nivel_ensino_cad_pop.php');"; - if ($this->ref_cod_instituicao) { - $script = ""; - } - else { - $script = ""; - } - - $this->campoLista('ref_cod_nivel_ensino', 'Nível Ensino', $opcoes, - $this->ref_cod_nivel_ensino, '', FALSE, '', $script); + $qtd_habilitacao = (count($this->habilitacao_curso) == 0) ? + 1 : (count($this->habilitacao_curso) + 1); - // Tipo ensino - $opcoes = array('' => 'Selecione'); + if (is_numeric($this->cod_curso) && $_POST['incluir'] != 'S' && empty($_POST['excluir_'])) { + $obj = new clsPmieducarHabilitacaoCurso(null, $this->cod_curso); + $registros = $obj->lista(null, $this->cod_curso); - if ($this->ref_cod_instituicao) { - $objTemp = new clsPmieducarTipoEnsino(); - $objTemp->setOrderby("nm_tipo"); - $lista = $objTemp->lista(NULL, NULL, NULL, NULL, NULL, NULL, 1, - $this->ref_cod_instituicao); + if ($registros) { + foreach ($registros as $campo) { + $this->habilitacao_curso[$campo[$qtd_habilitacao]]['ref_cod_habilitacao_'] = $campo['ref_cod_habilitacao']; - if (is_array($lista) && count($lista)) { - foreach ($lista as $registro) { - $opcoes[$registro['cod_tipo_ensino']] = $registro['nm_tipo']; + $qtd_habilitacao++; + } + } } - } - } - - $script = "javascript:showExpansivelIframe(520, 150, 'educar_tipo_ensino_cad_pop.php');"; - if ($this->ref_cod_instituicao) { - $script = ""; - } - else { - $script = ""; - } - - $this->campoLista('ref_cod_tipo_ensino', 'Tipo Ensino', $opcoes, - $this->ref_cod_tipo_ensino, '', FALSE, '', $script); - - // Tipo regime - $opcoes = array('' => 'Selecione'); + if ($_POST['habilitacao']) { + $this->habilitacao_curso[$qtd_habilitacao]['ref_cod_habilitacao_'] = $_POST['habilitacao']; - if ($this->ref_cod_instituicao) { - $objTemp = new clsPmieducarTipoRegime(); - $objTemp->setOrderby('nm_tipo'); - - $lista = $objTemp->lista(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - 1, $this->ref_cod_instituicao); - - if (is_array($lista) && count($lista)) { - foreach ($lista as $registro) { - $opcoes[$registro['cod_tipo_regime']] = $registro['nm_tipo']; + $qtd_habilitacao++; + unset($this->habilitacao); } - } - } - - $script = "javascript:showExpansivelIframe(520, 120, 'educar_tipo_regime_cad_pop.php');"; - - if ($this->ref_cod_instituicao) { - $script = ""; - } - else { - $script = ""; - } - - $this->campoLista('ref_cod_tipo_regime', 'Tipo Regime', $opcoes, - $this->ref_cod_tipo_regime, '', FALSE, '', $script, FALSE, FALSE); - // Outros campos - $this->campoTexto('nm_curso', 'Curso', $this->nm_curso, 30, 255, TRUE); + // primary keys + $this->campoOculto('cod_curso', $this->cod_curso); + + $obrigatorio = true; + include('include/pmieducar/educar_campo_lista.php'); + + // Nível ensino + $opcoes = [ '' => 'Selecione' ]; + + if ($this->ref_cod_instituicao) { + $objTemp = new clsPmieducarNivelEnsino(); + $lista = $objTemp->lista( + null, + null, + null, + null, + null, + null, + null, + null, + null, + 1, + $this->ref_cod_instituicao + ); + + if (is_array($lista) && count($lista)) { + foreach ($lista as $registro) { + $opcoes[$registro['cod_nivel_ensino']] = $registro['nm_nivel']; + } + } + } - $this->campoTexto('sgl_curso', 'Sigla Curso', $this->sgl_curso, 15, 15, false); + $script = 'javascript:showExpansivelIframe(520, 230, \'educar_nivel_ensino_cad_pop.php\');'; + if ($this->ref_cod_instituicao) { + $script = ""; + } else { + $script = ""; + } - $this->campoNumero('qtd_etapas', 'Quantidade Etapas', $this->qtd_etapas, 2, 2, TRUE); + $this->campoLista( + 'ref_cod_nivel_ensino', + 'Nível Ensino', + $opcoes, + $this->ref_cod_nivel_ensino, + '', + false, + '', + $script + ); + + // Tipo ensino + $opcoes = ['' => 'Selecione']; + + if ($this->ref_cod_instituicao) { + $objTemp = new clsPmieducarTipoEnsino(); + $objTemp->setOrderby('nm_tipo'); + $lista = $objTemp->lista( + null, + null, + null, + null, + null, + null, + 1, + $this->ref_cod_instituicao + ); + + if (is_array($lista) && count($lista)) { + foreach ($lista as $registro) { + $opcoes[$registro['cod_tipo_ensino']] = $registro['nm_tipo']; + } + } + } - if (is_numeric($this->hora_falta)) { - $this->campoMonetario('hora_falta', 'Hora Falta', - number_format($this->hora_falta, 2, ',', ''), 5, 5, FALSE, '', '', ''); - } - else { - $this->campoMonetario('hora_falta', 'Hora Falta', $this->hora_falta, 5, 5, - FALSE, '', '', ''); - } + $script = 'javascript:showExpansivelIframe(520, 150, \'educar_tipo_ensino_cad_pop.php\');'; + if ($this->ref_cod_instituicao) { + $script = ""; + } else { + $script = ""; + } - $this->campoMonetario('carga_horaria', 'Carga Horária', - $this->carga_horaria, 7, 7, TRUE); + $this->campoLista( + 'ref_cod_tipo_ensino', + 'Tipo Ensino', + $opcoes, + $this->ref_cod_tipo_ensino, + '', + false, + '', + $script + ); + + // Tipo regime + $opcoes = ['' => 'Selecione']; + + if ($this->ref_cod_instituicao) { + $objTemp = new clsPmieducarTipoRegime(); + $objTemp->setOrderby('nm_tipo'); + + $lista = $objTemp->lista( + null, + null, + null, + null, + null, + null, + null, + null, + 1, + $this->ref_cod_instituicao + ); + + if (is_array($lista) && count($lista)) { + foreach ($lista as $registro) { + $opcoes[$registro['cod_tipo_regime']] = $registro['nm_tipo']; + } + } + } - $this->campoTexto('ato_poder_publico', 'Ato Poder Público', - $this->ato_poder_publico, 30, 255, FALSE); + $script = 'javascript:showExpansivelIframe(520, 120, \'educar_tipo_regime_cad_pop.php\');'; - $this->campoOculto('excluir_', ''); - $qtd_habilitacao = 1; - $aux; + if ($this->ref_cod_instituicao) { + $script = ""; + } else { + $script = ""; + } - $this->campoQuebra(); - if ($this->habilitacao_curso) { - foreach ($this->habilitacao_curso as $campo) { - if ($this->excluir_ == $campo["ref_cod_habilitacao_"]) { - $this->habilitacao_curso[$campo["ref_cod_habilitacao"]] = NULL; - $this->excluir_ = NULL; + $this->campoLista( + 'ref_cod_tipo_regime', + 'Tipo Regime', + $opcoes, + $this->ref_cod_tipo_regime, + '', + false, + '', + $script, + false, + false + ); + + // Outros campos + $this->campoTexto('nm_curso', 'Curso', $this->nm_curso, 30, 255, true); + + $this->campoTexto('sgl_curso', 'Sigla Curso', $this->sgl_curso, 15, 15, false); + + $this->campoNumero('qtd_etapas', 'Quantidade Etapas', $this->qtd_etapas, 2, 2, true); + + if (is_numeric($this->hora_falta)) { + $this->campoMonetario( + 'hora_falta', + 'Hora Falta', + number_format($this->hora_falta, 2, ',', ''), + 5, + 5, + false, + '', + '', + '' + ); + } else { + $this->campoMonetario( + 'hora_falta', + 'Hora Falta', + $this->hora_falta, + 5, + 5, + false, + '', + '', + '' + ); } - else - { - $obj_habilitacao = new clsPmieducarHabilitacao($campo["ref_cod_habilitacao_"]); - $obj_habilitacao_det = $obj_habilitacao->detalhe(); - $nm_habilitacao = $obj_habilitacao_det["nm_tipo"]; - $this->campoTextoInv("ref_cod_habilitacao_{$campo["ref_cod_habilitacao_"]}", - '', $nm_habilitacao, 30, 255, FALSE, FALSE, FALSE, '', - "__nome}.submit();\">" ); + $this->campoMonetario( + 'carga_horaria', + 'Carga Horária', + $this->carga_horaria, + 7, + 7, + true + ); + + $this->campoTexto( + 'ato_poder_publico', + 'Ato Poder Público', + $this->ato_poder_publico, + 30, + 255, + false + ); + + $this->campoOculto('excluir_', ''); + $qtd_habilitacao = 1; + $aux; + + $this->campoQuebra(); + if ($this->habilitacao_curso) { + foreach ($this->habilitacao_curso as $campo) { + if ($this->excluir_ == $campo['ref_cod_habilitacao_']) { + $this->habilitacao_curso[$campo['ref_cod_habilitacao']] = null; + $this->excluir_ = null; + } else { + $obj_habilitacao = new clsPmieducarHabilitacao($campo['ref_cod_habilitacao_']); + $obj_habilitacao_det = $obj_habilitacao->detalhe(); + $nm_habilitacao = $obj_habilitacao_det['nm_tipo']; + + $this->campoTextoInv( + "ref_cod_habilitacao_{$campo['ref_cod_habilitacao_']}", + '', + $nm_habilitacao, + 30, + 255, + false, + false, + false, + '', + "__nome}.submit();\">" + ); + + $aux[$qtd_habilitacao]['ref_cod_habilitacao_'] = $campo['ref_cod_habilitacao_']; + + $qtd_habilitacao++; + } + } - $aux[$qtd_habilitacao]["ref_cod_habilitacao_"] = $campo["ref_cod_habilitacao_"]; + unset($this->habilitacao_curso); + $this->habilitacao_curso = $aux; + } - $qtd_habilitacao++; + $this->campoOculto('habilitacao_curso', serialize($this->habilitacao_curso)); + + // Habilitação + $opcoes = ['' => 'Selecione']; + + if ($this->ref_cod_instituicao) { + $objTemp = new clsPmieducarHabilitacao(); + $objTemp->setOrderby('nm_tipo'); + + $lista = $objTemp->lista( + null, + null, + null, + null, + null, + null, + null, + null, + null, + 1, + $this->ref_cod_instituicao + ); + + if (is_array($lista) && count($lista)) { + foreach ($lista as $registro) { + $opcoes[$registro['cod_habilitacao']] = $registro['nm_tipo']; + } + } } - } - unset($this->habilitacao_curso); - $this->habilitacao_curso = $aux; + $script = 'javascript:showExpansivelIframe(520, 225, \'educar_habilitacao_cad_pop.php\');'; + $script = ""; + + $this->campoLista( + 'habilitacao', + 'Habilitação', + $opcoes, + $this->habilitacao, + '', + false, + '', + "__nome}.submit();\">{$script}", + false, + false + ); + $this->campoOculto('incluir', ''); + $this->campoQuebra(); + + // Padrão ano escolar + $this->campoCheck('padrao_ano_escolar', 'Padrão Ano Escolar', $this->padrao_ano_escolar); + + $this->campoCheck('multi_seriado', 'Multi seriado', $this->multi_seriado); + + // Objetivo do curso + $this->campoMemo( + 'objetivo_curso', + 'Objetivo Curso', + $this->objetivo_curso, + 60, + 5, + false + ); + + // Público alvo + $this->campoMemo( + 'publico_alvo', + 'Público Alvo', + $this->publico_alvo, + 60, + 5, + false + ) ; + + $resources = [ + null => 'Selecione', + 1 => 'Ensino regular', + 2 => 'Educação especial', + 3 => 'Educação jovens e adultos', + 4 => 'Educação profissional' + ]; + + $options = ['label' => 'Modalidade do curso', 'resources' => $resources, 'value' => $this->modalidade_curso]; + $this->inputsHelper()->select('modalidade_curso', $options); + + $helperOptions = ['objectName' => 'etapacurso']; + $options = ['label' => 'Etapas que o curso contêm', 'size' => 50, 'required' => false, 'options' => ['value' => null]]; + + $this->inputsHelper()->multipleSearchEtapacurso('', $options, $helperOptions); } - $this->campoOculto('habilitacao_curso', serialize($this->habilitacao_curso)); - - // Habilitação - $opcoes = array('' => 'Selecione'); - - if ($this->ref_cod_instituicao) { - $objTemp = new clsPmieducarHabilitacao(); - $objTemp->setOrderby('nm_tipo'); + public function Novo() + { + if ($this->habilitacao_curso && $this->incluir != 'S' && empty($this->excluir_)) { + $this->carga_horaria = str_replace('.', '', $this->carga_horaria); + $this->carga_horaria = str_replace(',', '.', $this->carga_horaria); + $this->hora_falta = str_replace('.', '', $this->hora_falta); + $this->hora_falta = str_replace(',', '.', $this->hora_falta); + + $this->padrao_ano_escolar = is_null($this->padrao_ano_escolar) ? 0 : 1; + $this->multi_seriado = is_null($this->multi_seriado) ? 0 : 1; + + $obj = new clsPmieducarCurso( + null, + $this->pessoa_logada, + $this->ref_cod_tipo_regime, + $this->ref_cod_nivel_ensino, + $this->ref_cod_tipo_ensino, + null, + $this->nm_curso, + $this->sgl_curso, + $this->qtd_etapas, + null, + null, + null, + null, + $this->carga_horaria, + $this->ato_poder_publico, + null, + $this->objetivo_curso, + $this->publico_alvo, + null, + null, + 1, + null, + $this->ref_cod_instituicao, + $this->padrao_ano_escolar, + $this->hora_falta, + null, + $this->multi_seriado + ); + $obj->modalidade_curso = $this->modalidade_curso; + + $this->cod_curso = $cadastrou = $obj->cadastra(); + if ($cadastrou) { + $curso = new clsPmieducarCurso($this->cod_curso); + $curso = $curso->detalhe(); + + $auditoria = new clsModulesAuditoriaGeral('curso', $this->pessoa_logada, $this->cod_curso); + $auditoria->inclusao($curso); + + $this->gravaEtapacurso($cadastrou); + $this->habilitacao_curso = unserialize(urldecode($this->habilitacao_curso)); + + if ($this->habilitacao_curso) { + foreach ($this->habilitacao_curso as $campo) { + $obj = new clsPmieducarHabilitacaoCurso( + $campo['ref_cod_habilitacao_'], + $cadastrou + ); + + $cadastrou2 = $obj->cadastra(); + + if (!$cadastrou2) { + $this->mensagem = 'Cadastro não realizado.
'; + echo ""; + + return false; + } + } + } + + $this->mensagem .= 'Cadastro efetuado com sucesso.
'; + header('Location: educar_curso_lst.php'); + die(); + } - $lista = $objTemp->lista(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, 1, $this->ref_cod_instituicao); + $this->mensagem = 'Cadastro não realizado.
'; + echo ""; - if (is_array($lista) && count($lista)) { - foreach ($lista as $registro) { - $opcoes[$registro['cod_habilitacao']] = $registro['nm_tipo']; + return false; } - } - } - - $script = "javascript:showExpansivelIframe(520, 225, 'educar_habilitacao_cad_pop.php');"; - $script = ""; - - $this->campoLista('habilitacao', 'Habilitação', $opcoes, - $this->habilitacao, '', FALSE, '', - "__nome}.submit();\">{$script}", - FALSE, FALSE); - $this->campoOculto('incluir', ''); - $this->campoQuebra(); - - // Padrão ano escolar - $this->campoCheck('padrao_ano_escolar', 'Padrão Ano Escolar', $this->padrao_ano_escolar); - - $this->campoCheck('multi_seriado', 'Multi seriado', $this->multi_seriado); - - // Objetivo do curso - $this->campoMemo('objetivo_curso', 'Objetivo Curso', $this->objetivo_curso, - 60, 5, FALSE); - - // Público alvo - $this->campoMemo('publico_alvo', 'Público Alvo', $this->publico_alvo, - 60, 5, FALSE); - - $resources = array(null => 'Selecione', - 1 => Portabilis_String_Utils::toLatin1('Ensino regular'), - 2 => Portabilis_String_Utils::toLatin1('Educação especial'), - 3 => Portabilis_String_Utils::toLatin1('Educação jovens e adultos'), - 4 => Portabilis_String_Utils::toLatin1('Educação profissional')); - - $options = array('label' => Portabilis_String_Utils::toLatin1('Modalidade do curso'), 'resources' => $resources, 'value' => $this->modalidade_curso); - $this->inputsHelper()->select('modalidade_curso', $options); - - $helperOptions = array('objectName' => 'etapacurso'); - $options = array('label' => 'Etapas que o curso contêm', 'size' => 50, 'required' => false, - 'options' => array('value' => null)); - $this->inputsHelper()->multipleSearchEtapacurso('', $options, $helperOptions); - } - - function Novo() - { - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - - if ($this->habilitacao_curso && $this->incluir != 'S' && empty($this->excluir_)) { - $this->carga_horaria = str_replace('.', '', $this->carga_horaria); - $this->carga_horaria = str_replace(',', '.', $this->carga_horaria); - $this->hora_falta = str_replace('.', '', $this->hora_falta); - $this->hora_falta = str_replace(',', '.', $this->hora_falta); - - $this->padrao_ano_escolar = is_null($this->padrao_ano_escolar) ? 0 : 1; - $this->multi_seriado = is_null($this->multi_seriado) ? 0 : 1; - - $obj = new clsPmieducarCurso(NULL, $this->pessoa_logada, - $this->ref_cod_tipo_regime, $this->ref_cod_nivel_ensino, - $this->ref_cod_tipo_ensino, NULL, $this->nm_curso, $this->sgl_curso, - $this->qtd_etapas, NULL, NULL, NULL, NULL, $this->carga_horaria, - $this->ato_poder_publico, NULL, $this->objetivo_curso, - $this->publico_alvo, NULL, NULL, 1, NULL, $this->ref_cod_instituicao, - $this->padrao_ano_escolar, $this->hora_falta, NULL, $this->multi_seriado); - $obj->modalidade_curso = $this->modalidade_curso; - - $this->cod_curso = $cadastrou = $obj->cadastra(); - if ($cadastrou) { - $curso = new clsPmieducarCurso($this->cod_curso); - $curso = $curso->detalhe(); - - $auditoria = new clsModulesAuditoriaGeral("curso", $this->pessoa_logada, $this->cod_curso); - $auditoria->inclusao($curso); - - $this->gravaEtapacurso($cadastrou); - $this->habilitacao_curso = unserialize(urldecode($this->habilitacao_curso)); + return true; + } - if ($this->habilitacao_curso) { - foreach ($this->habilitacao_curso as $campo) { - $obj = new clsPmieducarHabilitacaoCurso($campo["ref_cod_habilitacao_"], - $cadastrou); + public function Editar() + { + if ($this->habilitacao_curso && $this->incluir != 'S' && empty($this->excluir_)) { + $this->carga_horaria = str_replace('.', '', $this->carga_horaria); + $this->carga_horaria = str_replace(',', '.', $this->carga_horaria); + $this->hora_falta = str_replace('.', '', $this->hora_falta); + $this->hora_falta = str_replace(',', '.', $this->hora_falta); + + $this->padrao_ano_escolar = is_null($this->padrao_ano_escolar) ? 0 : 1; + $this->multi_seriado = is_null($this->multi_seriado) ? 0 : 1; + + $obj = new clsPmieducarCurso( + $this->cod_curso, + null, + $this->ref_cod_tipo_regime, + $this->ref_cod_nivel_ensino, + $this->ref_cod_tipo_ensino, + null, + $this->nm_curso, + $this->sgl_curso, + $this->qtd_etapas, + null, + null, + null, + null, + $this->carga_horaria, + $this->ato_poder_publico, + null, + $this->objetivo_curso, + $this->publico_alvo, + null, + null, + 1, + $this->pessoa_logada, + $this->ref_cod_instituicao, + $this->padrao_ano_escolar, + $this->hora_falta, + null, + $this->multi_seriado + ); + $obj->modalidade_curso = $this->modalidade_curso; + + $detalheAntigo = $obj->detalhe(); + $alterouPadraoAnoEscolar = $detalheAntigo['padrao_ano_escolar'] != $this->padrao_ano_escolar; + $editou = $obj->edita(); + if ($editou) { + $detalheAtual = $obj->detalhe(); + $auditoria = new clsModulesAuditoriaGeral('curso', $this->pessoa_logada, $this->cod_curso); + $auditoria->alteracao($detalheAntigo, $detalheAtual); + + $this->gravaEtapacurso($this->cod_curso); + $this->habilitacao_curso = unserialize(urldecode($this->habilitacao_curso)); + $obj = new clsPmieducarHabilitacaoCurso(null, $this->cod_curso); + $excluiu = $obj->excluirTodos(); + + if ($excluiu) { + if ($this->habilitacao_curso) { + foreach ($this->habilitacao_curso as $campo) { + $obj = new clsPmieducarHabilitacaoCurso( + $campo['ref_cod_habilitacao_'], + $this->cod_curso + ); + + $cadastrou2 = $obj->cadastra(); + + if (!$cadastrou2) { + $this->mensagem = 'Edição não realizada.
'; + echo ""; + + return false; + } + } + } + } + + if ($alterouPadraoAnoEscolar) { + $this->updateClassStepsForCourse($this->cod_curso, $this->padrao_ano_escolar, date("Y")); + } + + + $this->mensagem .= 'Edição efetuada com sucesso.
'; + header('Location: educar_curso_lst.php'); + die(); + } - $cadastrou2 = $obj->cadastra(); + $this->mensagem = 'Edição não realizada.
'; + echo ""; - if (!$cadastrou2) { - $this->mensagem = "Cadastro não realizado.
"; - echo ""; - return FALSE; - } - } + return false; } - $this->mensagem .= "Cadastro efetuado com sucesso.
"; - header("Location: educar_curso_lst.php"); - die(); - } - - $this->mensagem = "Cadastro não realizado.
"; - echo ""; - return FALSE; + return true; } - return TRUE; - } - - function Editar() - { - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - - if ($this->habilitacao_curso && $this->incluir != 'S' && empty($this->excluir_)) { - $this->carga_horaria = str_replace('.', '', $this->carga_horaria); - $this->carga_horaria = str_replace(',', '.', $this->carga_horaria); - $this->hora_falta = str_replace('.', '', $this->hora_falta); - $this->hora_falta = str_replace(',', '.', $this->hora_falta); - - $this->padrao_ano_escolar = is_null($this->padrao_ano_escolar) ? 0 : 1; - $this->multi_seriado = is_null($this->multi_seriado) ? 0 : 1; - - $obj = new clsPmieducarCurso($this->cod_curso, NULL, $this->ref_cod_tipo_regime, - $this->ref_cod_nivel_ensino, $this->ref_cod_tipo_ensino, NULL, - $this->nm_curso, $this->sgl_curso, $this->qtd_etapas, NULL, NULL, NULL, - NULL, $this->carga_horaria, $this->ato_poder_publico, NULL, - $this->objetivo_curso, $this->publico_alvo, NULL, NULL, 1, - $this->pessoa_logada, $this->ref_cod_instituicao, - $this->padrao_ano_escolar, $this->hora_falta, NULL, $this->multi_seriado); - $obj->modalidade_curso = $this->modalidade_curso; - - $detalheAntigo = $obj->detalhe(); - $editou = $obj->edita(); - if ($editou) { - - $detalheAtual = $obj->detalhe(); - $auditoria = new clsModulesAuditoriaGeral("curso", $this->pessoa_logada, $this->cod_curso); - $auditoria->alteracao($detalheAntigo, $detalheAtual); - - $this->gravaEtapacurso($this->cod_curso); - $this->habilitacao_curso = unserialize(urldecode($this->habilitacao_curso)); - $obj = new clsPmieducarHabilitacaoCurso(NULL, $this->cod_curso); - $excluiu = $obj->excluirTodos(); - + public function Excluir() + { + $obj = new clsPmieducarCurso( + $this->cod_curso, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + 0, + $this->pessoa_logada + ); + + $curso = $obj->detalhe(); + $excluiu = $obj->excluir(); if ($excluiu) { - if ($this->habilitacao_curso) { - foreach ($this->habilitacao_curso as $campo) { - $obj = new clsPmieducarHabilitacaoCurso( - $campo["ref_cod_habilitacao_"], $this->cod_curso - ); - - $cadastrou2 = $obj->cadastra(); - - if (!$cadastrou2) { - $this->mensagem = "Edição não realizada.
"; - echo ""; - return FALSE; - } - } - } + $auditoria = new clsModulesAuditoriaGeral('curso', $this->pessoa_logada, $this->cod_curso); + $auditoria->exclusao($curso); + $this->mensagem .= 'Exclusão efetuada com sucesso.
'; + header('Location: educar_curso_lst.php'); + die(); } - $this->mensagem .= "Edição efetuada com sucesso.
"; - header("Location: educar_curso_lst.php"); - die(); - } + $this->mensagem = 'Exclusão não realizada.
'; + echo ""; - $this->mensagem = "Edição não realizada.
"; - echo ""; - return FALSE; + return false; } - return TRUE; - } - - function Excluir() - { - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - - $obj = new clsPmieducarCurso($this->cod_curso, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, 0, $this->pessoa_logada); - - $curso = $obj->detalhe(); - $excluiu = $obj->excluir(); - if ($excluiu) { - - $auditoria = new clsModulesAuditoriaGeral("curso", $this->pessoa_logada, $this->cod_curso); - $auditoria->exclusao($curso); - $this->mensagem .= "Exclusão efetuada com sucesso.
"; - header("Location: educar_curso_lst.php"); - die(); + public function gravaEtapacurso($cod_curso) + { + Portabilis_Utils_Database::fetchPreparedQuery('DELETE FROM etapas_curso_educacenso WHERE curso_id = $1', ['params' => [$cod_curso]]); + foreach ($this->getRequest()->etapacurso as $etapaId) { + if (! empty($etapaId)) { + Portabilis_Utils_Database::fetchPreparedQuery('INSERT INTO etapas_curso_educacenso VALUES ($1 , $2)', ['params' => [$etapaId, $cod_curso] ]); + } + } } - $this->mensagem = "Exclusão não realizada.
"; - echo ""; - return FALSE; - } + public function updateClassStepsForCourse($courseCode, $standerdSchoolYear, $currentYear) + { + $classStepsObject = new ClsPmieducarTurmaModulo(); - function gravaEtapacurso($cod_curso){ - Portabilis_Utils_Database::fetchPreparedQuery('DELETE FROM etapas_curso_educacenso WHERE curso_id = $1', array('params' => array($cod_curso))); - foreach ($this->getRequest()->etapacurso as $etapaId) { - if (! empty($etapaId)) { - Portabilis_Utils_Database::fetchPreparedQuery('INSERT INTO etapas_curso_educacenso VALUES ($1 , $2)', array('params' => array($etapaId, $cod_curso) )); - } + $classStepsObject->removeStepsOfClassesForCourseAndYear($courseCode, $currentYear); + + if ($standerdSchoolYear == 0) { + $classStepsObject->copySchoolStepsIntoClassesForCourseAndYear($courseCode, $currentYear); + } } - } } // Instancia objeto de página @@ -692,14 +831,14 @@ function getHabilitacao(xml_habilitacao) xml_habilitacao.envia("educar_habilitacao_xml.php?ins="+campoInstituicao); if (this.value == '') { - $('img_nivel_ensino').style.display = 'none;'; - $('img_tipo_regime').style.display = 'none;'; - $('img_tipo_ensino').style.display = 'none;'; + $('img_nivel_ensino').style.display = 'none;'; + $('img_tipo_regime').style.display = 'none;'; + $('img_tipo_ensino').style.display = 'none;'; } else { - $('img_nivel_ensino').style.display = ''; - $('img_tipo_regime').style.display = ''; - $('img_tipo_ensino').style.display = ''; + $('img_nivel_ensino').style.display = ''; + $('img_tipo_regime').style.display = ''; + $('img_tipo_ensino').style.display = ''; } } @@ -732,10 +871,10 @@ function fixupEtapacursoSize(){ }; var options = { - url : getResourceUrlBuilder.buildUrl('/module/Api/etapacurso', 'etapacurso', additionalVars), + url : getResourceUrlBuilder.buildUrl('/module/Api/etapacurso', 'etapacurso', additionalVars), dataType : 'json', - data : {}, - success : handleGetEtapacurso, + data : {}, + success : handleGetEtapacurso, }; getResource(options); diff --git a/ieducar/intranet/educar_escola_serie_cad.php b/ieducar/intranet/educar_escola_serie_cad.php index 9ec8cf2b0a..1f25056a58 100644 --- a/ieducar/intranet/educar_escola_serie_cad.php +++ b/ieducar/intranet/educar_escola_serie_cad.php @@ -561,15 +561,6 @@ function Editar() } } } - - //Verifica/limpa disciplinas não alteradas quando a escola/série for editada e tiver disciplinas marcadas - //não padrão do ano letivo. - $obj_ano_letivo = new clsPmieducarEscolaAnoLetivo(); - $existe_ano_andamento = $obj_ano_letivo->lista($this->ref_cod_escola, null, null, null, 1, null, null, null, null, 1); - - foreach ($existe_ano_andamento as $reg) { - CleanComponentesCurriculares::destroyOldResources($reg['ano']); - } } $this->mensagem .= 'Edição efetuada com sucesso.
'; diff --git a/ieducar/intranet/educar_historico_escolar_cad.php b/ieducar/intranet/educar_historico_escolar_cad.php index e78f39ff9b..9337c5d679 100644 --- a/ieducar/intranet/educar_historico_escolar_cad.php +++ b/ieducar/intranet/educar_historico_escolar_cad.php @@ -1,30 +1,4 @@ SetTitulo( "{$this->_instituicao} i-Educar - Histórico Escolar" ); - $this->processoAp = "578"; + $this->SetTitulo("{$this->_instituicao} i-Educar - Histórico Escolar"); + $this->processoAp = '578'; $this->addEstilo('localizacaoSistema'); } } class indice extends clsCadastro { - /** - * Referencia pega da session para o idpes do usuario atual - * - * @var int - */ - var $pessoa_logada; - - var $ref_cod_aluno; - var $sequencial; - var $ref_usuario_exc; - var $ref_usuario_cad; - var $ano; - var $carga_horaria; - var $dias_letivos; - var $ref_cod_escola; - var $escola; - var $escola_cidade; - var $escola_uf; - var $observacao; - var $aprovado; - var $data_cadastro; - var $data_exclusao; - var $ativo; - var $posicao; - - var $ref_cod_instituicao; - var $nm_serie; - var $origem; - var $extra_curricular; - var $ref_cod_matricula; - - var $faltas_globalizadas; - var $cb_faltas_globalizadas; - var $frequencia; - -//------INCLUI DISCIPLINA------// - var $historico_disciplinas; - var $nm_disciplina; - var $nota; - var $faltas; - var $ordenamento; - var $carga_horaria_disciplina; - var $disciplinaDependencia; - var $excluir_disciplina; - var $ultimo_sequencial; - - var $aceleracao; - var $dependencia; - - function Inicializar() + public $ref_cod_aluno; + + public $sequencial; + + public $ref_usuario_exc; + + public $ref_usuario_cad; + + public $ano; + + public $carga_horaria; + + public $dias_letivos; + + public $ref_cod_escola; + + public $escola; + + public $escola_cidade; + + public $escola_uf; + + public $observacao; + + public $aprovado; + + public $data_cadastro; + + public $data_exclusao; + + public $ativo; + + public $posicao; + + public $ref_cod_instituicao; + + public $nm_curso; + + public $nm_serie; + + public $origem; + + public $extra_curricular; + + public $ref_cod_matricula; + + public $faltas_globalizadas; + + public $cb_faltas_globalizadas; + + public $frequencia; + + //------INCLUI DISCIPLINA------// + + public $historico_disciplinas; + + public $nm_disciplina; + + public $nota; + + public $faltas; + + public $ordenamento; + + public $carga_horaria_disciplina; + + public $disciplinaDependencia; + + public $excluir_disciplina; + + public $ultimo_sequencial; + + public $aceleracao; + + public $dependencia; + + public function Inicializar() { - $retorno = "Novo"; - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); + $retorno = 'Novo'; - $this->sequencial=$_GET["sequencial"]; - $this->ref_cod_aluno=$_GET["ref_cod_aluno"]; + $this->sequencial = $_GET['sequencial']; + $this->ref_cod_aluno = $_GET['ref_cod_aluno']; $obj_permissoes = new clsPermissoes(); - $obj_permissoes->permissao_cadastra( 578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); - - if( is_numeric( $this->ref_cod_aluno ) && is_numeric( $this->sequencial ) ) - { - $obj = new clsPmieducarHistoricoEscolar( $this->ref_cod_aluno, $this->sequencial ); - $registro = $obj->detalhe(); - if( $registro ) - { - foreach( $registro AS $campo => $val ) // passa todos os valores obtidos no registro para atributos do objeto + $obj_permissoes->permissao_cadastra(578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); + + if (is_numeric($this->ref_cod_aluno) && is_numeric($this->sequencial)) { + $obj = new clsPmieducarHistoricoEscolar($this->ref_cod_aluno, $this->sequencial); + $registro = $obj->detalhe(); + + if ($registro) { + foreach ($registro as $campo => $val) { // passa todos os valores obtidos no registro para atributos do objeto $this->$campo = $val; + } - if (!$this->origem) - { - header( "Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); + if (!$this->origem) { + header("Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); die(); } - if( $obj_permissoes->permissao_excluir( 578, $this->pessoa_logada, 7 ) ) - { + if ($obj_permissoes->permissao_excluir(578, $this->pessoa_logada, 7)) { $this->fexcluir = true; } - if(!isset($_GET['copia'])) - $retorno = "Editar"; - else + + if (!isset($_GET['copia'])) { + $retorno = 'Editar'; + } else { $this->fexcluir = false; + } } } - $this->url_cancelar = ($retorno == "Editar") ? "educar_historico_escolar_det.php?ref_cod_aluno={$registro["ref_cod_aluno"]}&sequencial={$registro["sequencial"]}" : "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"; - $this->nome_url_cancelar = "Cancelar"; - $localizacao = new LocalizacaoSistema(); - $localizacao->entradaCaminhos( array( - $_SERVER['SERVER_NAME']."/intranet" => "Início", - "educar_index.php" => "Escola", - "" => "Atualização de históricos escolares" - )); - $this->enviaLocalizacao($localizacao->montar()); - $this->dependencia = dbBool($this->dependencia); + + $this->url_cancelar = ($retorno == 'Editar') ? "educar_historico_escolar_det.php?ref_cod_aluno={$registro['ref_cod_aluno']}&sequencial={$registro['sequencial']}" : "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"; + $this->nome_url_cancelar = 'Cancelar'; + $this->dependencia = dbBool($this->dependencia); + + $this->breadcrumb('Atualização de históricos escolares', [ + url('intranet/educar_index.php') => 'Escola', + ]); + return $retorno; } - function Gerar() + public function Gerar() { - if (isset($_GET["ref_cod_aluno"], $_GET["sequencial"])) { - $objCodNomeEscola = new clsPmieducarHistoricoEscolar($_GET["ref_cod_aluno"], $_GET["sequencial"]); + if (isset($_GET['ref_cod_aluno'], $_GET['sequencial'])) { + $objCodNomeEscola = new clsPmieducarHistoricoEscolar($_GET['ref_cod_aluno'], $_GET['sequencial']); $registro = $objCodNomeEscola->detalhe(); if ($registro) { @@ -158,407 +155,361 @@ function Gerar() } } - if( $_POST ) - foreach( $_POST AS $campo => $val ) - $this->$campo = ( !$this->$campo ) ? $val : $this->$campo ; + if ($_POST) { + foreach ($_POST as $campo => $val) { + $this->$campo = (!$this->$campo) ? $val : $this->$campo; + } + } // primary keys - $this->campoOculto( "ref_cod_aluno", $this->ref_cod_aluno ); - $this->campoOculto( "sequencial", $this->sequencial ); - $this->campoOculto("codigoEscola", $codigoEscola); - $this->campoOculto("nomeEscola", $nomeEscola); - $this->campoOculto("numeroSequencial", $_GET["sequencial"]); + $this->campoOculto('ref_cod_aluno', $this->ref_cod_aluno); + $this->campoOculto('sequencial', $this->sequencial); + $this->campoOculto('codigoEscola', $codigoEscola); + $this->campoOculto('nomeEscola', $nomeEscola); + $this->campoOculto('numeroSequencial', $_GET['sequencial']); + $obj_aluno = new clsPmieducarAluno(); - $lst_aluno = $obj_aluno->lista( $this->ref_cod_aluno,null,null,null,null,null,null,null,null,null,1 ); - if ( is_array($lst_aluno) ) - { + $lst_aluno = $obj_aluno->lista($this->ref_cod_aluno, null, null, null, null, null, null, null, null, null, 1); + + if (is_array($lst_aluno)) { $det_aluno = array_shift($lst_aluno); - $this->nm_aluno = $det_aluno["nome_aluno"]; - $this->campoRotulo( "nm_aluno", "Aluno", $this->nm_aluno ); + $this->nm_aluno = $det_aluno['nome_aluno']; + $this->campoRotulo('nm_aluno', 'Aluno', $this->nm_aluno); } $obj_nivelUser = new clsPermissoes(); $user_nivel = $obj_nivelUser->nivel_acesso($this->pessoa_logada); - if ($user_nivel != App_Model_NivelTipoUsuario::POLI_INSTITUCIONAL) - { + + if ($user_nivel != App_Model_NivelTipoUsuario::POLI_INSTITUCIONAL) { $obj_permissoes = new clsPermissoes(); - $this->ref_cod_instituicao = $obj_permissoes->getInstituicao($this->pessoa_logada ); + $this->ref_cod_instituicao = $obj_permissoes->getInstituicao($this->pessoa_logada); $habilitaCargaHoraria = $this->habilitaCargaHoraria($this->ref_cod_instituicao); } $obj_nivel = new clsPmieducarUsuario($this->pessoa_logada); $nivel_usuario = $obj_nivel->detalhe(); - if ($nivel_usuario['ref_cod_tipo_usuario'] == 1) - { + if ($nivel_usuario['ref_cod_tipo_usuario'] == 1) { $obj_instituicao = new clsPmieducarInstituicao(); - $lista = $obj_instituicao->lista(null,null,null,null,null,null,null,null,null,null,null,null,null,1); - $opcoes["1"] = "Selecione"; - if ( is_array( $lista ) && count( $lista ) ) - { - foreach ( $lista as $registro ) - { + $lista = $obj_instituicao->lista(null, null, null, null, null, null, null, null, null, null, null, null, null, 1); + $opcoes['1'] = 'Selecione'; + + if (is_array($lista) && count($lista)) { + foreach ($lista as $registro) { $opcoes["{$registro['cod_instituicao']}"] = "{$registro['nm_instituicao']}"; } } - $this->campoLista("ref_cod_instituicao", "Instituição", $opcoes, ""); - } - else - { + + $this->campoLista('ref_cod_instituicao', 'Instituição', $opcoes, ''); + } else { $obj_instituicao = new clsPmieducarInstituicao($nivel_usuario['ref_cod_instituicao']); $inst = $obj_instituicao->detalhe(); - $this->campoOculto("ref_cod_instituicao", $inst['cod_instituicao']); - $this->campoTexto("instituicao", "Instiuição", $inst['nm_instituicao'], 30, 255, false, false, false, "", "", "", "", true); + + $this->campoOculto('ref_cod_instituicao', $inst['cod_instituicao']); + $this->campoTexto('instituicao', 'Instiuição', $inst['nm_instituicao'], 30, 255, false, false, false, '', '', '', '', true); } - $opcoes = array("" => "Selecione"); + $opcoes = ['' => 'Selecione']; $listar_escolas = new clsPmieducarEscola(); $escolas = $listar_escolas->lista_escola(); - foreach ($escolas as $escola){ + foreach ($escolas as $escola) { $opcoes["{$escola['cod_escola']}"] = "{$escola['nome']}"; } $opcoes['outra'] = 'OUTRA'; - $this->campoLista("ref_cod_escola", "Escola", $opcoes, null, '', false, '', '', false, true); + $this->campoLista('ref_cod_escola', 'Escola', $opcoes, null, '', false, '', '', false, true); - $escola_options = array( - 'required' => false, - 'label' => 'Nome da escola', - 'value' => $this->escola, - 'max_length' => 255, - 'size' => 80, - ); - $this->inputsHelper()->text('escola', $escola_options); + $escola_options = [ + 'required' => false, + 'label' => 'Nome da escola', + 'value' => $this->escola, + 'max_length' => 255, + 'size' => 80, + ]; + $this->inputsHelper()->text('escola', $escola_options); // text - $this->campoTexto( "escola_cidade", "Cidade da Escola", $this->escola_cidade, 30, 255, true ); + $this->campoTexto('escola_cidade', 'Cidade da Escola', $this->escola_cidade, 30, 255, true); - $det_uf[] = array(); - if($this->escola_uf) - { + $det_uf[] = []; + if ($this->escola_uf) { //busca pais do estado $obj_uf = new clsUf($this->escola_uf); $det_uf = $obj_uf->detalhe(); } - $lista_pais_origem = array('45' => "País da escola"); + $lista_pais_origem = ['45' => 'País da escola']; $obj_pais = new clsPais(); - $obj_pais_lista = $obj_pais->lista(null,null,null,"","","nome asc"); - if($obj_pais_lista) - { - foreach ($obj_pais_lista as $key => $pais) - { - $lista_pais_origem[$pais["idpais"]] = $pais["nome"]; + $obj_pais_lista = $obj_pais->lista(null, null, null, '', '', 'nome asc'); + if ($obj_pais_lista) { + foreach ($obj_pais_lista as $key => $pais) { + $lista_pais_origem[$pais['idpais']] = $pais['nome']; } } - $this->campoLista("idpais", "País da Escola", $lista_pais_origem, $det_uf['int_idpais'] ); + $this->campoLista('idpais', 'País da Escola', $lista_pais_origem, $det_uf['int_idpais']); $obj_uf = new clsUf(); - $lista_uf = $obj_uf->lista( false,false,$det_uf['int_idpais'],false,false, "sigla_uf" ); - $lista_estado = array( "SC" => "Selecione um país" ); - if( $lista_uf ) - { - foreach ($lista_uf as $uf) - { + $lista_uf = $obj_uf->lista(false, false, $det_uf['int_idpais'], false, false, 'sigla_uf'); + $lista_estado = ['SC' => 'Selecione um país']; + + if ($lista_uf) { + foreach ($lista_uf as $uf) { $lista_estado[$uf['sigla_uf']] = $uf['sigla_uf']; } } - $this->campoLista("escola_uf", "Estado da Escola", $lista_estado, $this->escola_uf ); - $this->campoTexto("nm_curso", "Curso", $this->nm_curso, 30, 255, false, false, false, _cl('historico.cadastro.curso_detalhe')); + $this->campoLista('escola_uf', 'Estado da Escola', $lista_estado, $this->escola_uf); + $this->campoTexto('nm_curso', 'Curso', $this->nm_curso, 30, 255, false, false, false, _cl('historico.cadastro.curso_detalhe')); $opcoesGradeCurso = getOpcoesGradeCurso(); - $this->campoLista( "historico_grade_curso_id", "Grade curso", $opcoesGradeCurso, $this->historico_grade_curso_id ); + $this->campoLista('historico_grade_curso_id', 'Grade curso', $opcoesGradeCurso, $this->historico_grade_curso_id); + + $this->campoTexto('nm_serie', _cl('historico.cadastro.serie'), $this->nm_serie, 30, 255, true); + $this->campoCheck('dependencia', 'Histórico de dependência', $this->dependencia); + $this->campoNumero('ano', 'Ano', $this->ano, 4, 4, true); - $this->campoTexto( "nm_serie", _cl('historico.cadastro.serie'), $this->nm_serie, 30, 255, true ); - $this->campoCheck("dependencia", "Histórico de dependência", $this->dependencia); - $this->campoNumero( "ano", "Ano", $this->ano, 4, 4, true ); if (validaControlePosicaoHistorico()) { - $this->campoNumero( "posicao", "Posição", $this->posicao, 1, 1, true, 'Informe a coluna equivalente a série/ano/etapa a qual o histórico pertence. Ex.: 1º ano informe 1, 2º ano informe 2' ); + $this->campoNumero('posicao', 'Posição', $this->posicao, 1, 1, true, 'Informe a coluna equivalente a série/ano/etapa a qual o histórico pertence. Ex.: 1º ano informe 1, 2º ano informe 2'); } - $this->campoNumero( "carga_horaria", "Carga Horária", $this->carga_horaria, 8, 8, false); - $this->campoCheck( "cb_faltas_globalizadas", "Faltas Globalizadas", is_numeric($this->faltas_globalizadas) ? 'on' : ''); - $this->campoNumero( "faltas_globalizadas", "Faltas Globalizadas", $this->faltas_globalizadas, 4, 4, false ); - $this->campoNumero( "dias_letivos", "Dias Letivos", $this->dias_letivos, 3, 3, false); - $this->campoMonetario( "frequencia", "Frequência", $this->frequencia, 8, 6, false ); - $this->campoCheck( "extra_curricular", "Extra-Curricular", $this->extra_curricular ); - $this->campoCheck( "aceleracao", "Aceleração", $this->aceleracao ); - - $obs_options = array( - 'required' => false, - 'label' => 'Observação', - 'value' => $this->observacao - ); - $this->inputsHelper()->textArea( 'observacao', $obs_options); - - $opcoes = array( "" => "Selecione", - 1 => "Aprovado", - 2 => "Reprovado", - 3 => "Cursando", - 4 => "Transferido", - 6 => 'Abandono', - 12 => 'Aprovado com dependência', - 13 => 'Aprovado pelo conselho', - 14 => 'Reprovado por faltas'); - $this->campoLista( "aprovado", "Situação", $opcoes, $this->aprovado ); - - $this->campoTexto( "registro", "Registro (arquivo)", $this->registro, 30, 50, false); - $this->campoTexto( "livro", "Livro", $this->livro, 30, 50, false); - $this->campoTexto( "folha", "Folha", $this->folha, 30, 50, false); - - // $this->campoCheck("dependencia", "Histórico de dependência", $this->dependencia); - - - //---------------------INCLUI DISCIPLINAS---------------------// - $this->campoQuebra(); - - //if ( $_POST["historico_disciplinas"] ) - //$this->historico_disciplinas = unserialize( urldecode( $_POST["historico_disciplinas"] ) ); - //$qtd_disciplinas = ( count( $this->historico_disciplinas ) == 0 ) ? 1 : ( count( $this->historico_disciplinas ) + 1); + $this->campoNumero('carga_horaria', 'Carga Horária', $this->carga_horaria, 8, 8, false); + $this->campoCheck('cb_faltas_globalizadas', 'Faltas Globalizadas', is_numeric($this->faltas_globalizadas) ? 'on' : ''); + $this->campoNumero('faltas_globalizadas', 'Faltas Globalizadas', $this->faltas_globalizadas, 4, 4, false); + $this->campoNumero('dias_letivos', 'Dias Letivos', $this->dias_letivos, 3, 3, false); + $this->campoMonetario('frequencia', 'Frequência', $this->frequencia, 8, 6, false); + $this->campoCheck('extra_curricular', 'Extra-Curricular', $this->extra_curricular); + $this->campoCheck('aceleracao', 'Aceleração', $this->aceleracao); + + $obs_options = [ + 'required' => false, + 'label' => 'Observação', + 'value' => $this->observacao + ]; + $this->inputsHelper()->textArea('observacao', $obs_options); + + $opcoes = [ + '' => 'Selecione', + 1 => 'Aprovado', + 2 => 'Reprovado', + 3 => 'Cursando', + 4 => 'Transferido', + 6 => 'Abandono', + 12 => 'Aprovado com dependência', + 13 => 'Aprovado pelo conselho', + 14 => 'Reprovado por faltas' + ]; + + $this->campoLista('aprovado', 'Situação', $opcoes, $this->aprovado); + $this->campoTexto('registro', 'Registro (arquivo)', $this->registro, 30, 50, false); + $this->campoTexto('livro', 'Livro', $this->livro, 30, 50, false); + $this->campoTexto('folha', 'Folha', $this->folha, 30, 50, false); + + //---------------------INCLUI DISCIPLINAS---------------------// + $this->campoQuebra(); - if( is_numeric( $this->ref_cod_aluno) && is_numeric( $this->sequencial) && !$_POST) - { + if (is_numeric($this->ref_cod_aluno) && is_numeric($this->sequencial) && !$_POST) { $obj = new clsPmieducarHistoricoDisciplinas(); - $obj->setOrderby("nm_disciplina ASC"); - $registros = $obj->lista( null, $this->ref_cod_aluno, $this->sequencial ); + $obj->setOrderby('nm_disciplina ASC'); + $registros = $obj->lista(null, $this->ref_cod_aluno, $this->sequencial); $qtd_disciplinas = 0; - if( $registros ) - { - foreach ( $registros AS $campo ) - { - $this->historico_disciplinas[$qtd_disciplinas][] = $campo["nm_disciplina"]; - $this->historico_disciplinas[$qtd_disciplinas][] = $campo["nota"]; - $this->historico_disciplinas[$qtd_disciplinas][] = $campo["faltas"]; - $this->historico_disciplinas[$qtd_disciplinas][] = $campo["carga_horaria_disciplina"]; - $this->historico_disciplinas[$qtd_disciplinas][] = $campo["ordenamento"]; - $this->historico_disciplinas[$qtd_disciplinas][] = dbBool($campo["dependencia"]) ? 1 : 0; - $this->historico_disciplinas[$qtd_disciplinas][] = $campo["sequencial"]; + + if ($registros) { + foreach ($registros as $campo) { + $this->historico_disciplinas[$qtd_disciplinas][] = $campo['nm_disciplina']; + $this->historico_disciplinas[$qtd_disciplinas][] = $campo['tipo_base']; + $this->historico_disciplinas[$qtd_disciplinas][] = $campo['nota']; + $this->historico_disciplinas[$qtd_disciplinas][] = $campo['faltas']; + $this->historico_disciplinas[$qtd_disciplinas][] = $campo['carga_horaria_disciplina']; + $this->historico_disciplinas[$qtd_disciplinas][] = $campo['ordenamento']; + $this->historico_disciplinas[$qtd_disciplinas][] = dbBool($campo['dependencia']) ? 1 : 0; + $this->historico_disciplinas[$qtd_disciplinas][] = $campo['sequencial']; $qtd_disciplinas++; } } } - - $this->campoTabelaInicio("notas","Notas",array("Disciplina","Nota","Faltas", 'C.H', "Ordem", "Dependência"),$this->historico_disciplinas); - - //$this->campoTexto( "nm_disciplina", "Disciplina", $this->nm_disciplina, 30, 255, false, false, false, '', '', 'autoCompleteComponentesCurricular(this)', 'onfocus' ); - $this->campoTexto( "nm_disciplina", "Disciplina", $this->nm_disciplina, 30, 255, false, false, false, '', '', '', 'onfocus' ); - - $this->campoTexto( "nota", "Nota", $this->nota, 10, 255, false ); - $this->campoNumero( "faltas", "Faltas", $this->faltas, 3, 3, false ); - $this->campoNumero( "carga_horaria_disciplina", "carga_horaria_disciplina", $this->carga_horaria_disciplina, 3, 3, false, NULL, NULL, NULL, NULL, NULL, $habilitaCargaHoraria ); - $this->campoNumero( "ordenamento", "ordenamento", $this->ordenamento, 3, 3, false ); - $options = array('label' => 'Dependência', 'value' => $this->disciplinaDependencia); + // Tipo Base + $tipoBase = ComponenteCurricular_Model_TipoBase::getInstance()->getEnums(); + + $this->campoTabelaInicio('notas', 'Notas', ['Disciplina', 'Base curricular', 'Nota', 'Faltas', 'C.H', 'Ordem', 'Dependência'], $this->historico_disciplinas); + $this->campoTexto('nm_disciplina', 'Disciplina', $this->nm_disciplina, 30, 255, false, false, false, '', '', '', 'onfocus'); + $this->campoLista('tipo_base', 'Base curricular', $tipoBase, $this->tipo_base, '', false, '', '', false, false); + $this->campoTexto('nota', 'Nota', $this->nota, 10, 255, false); + $this->campoNumero('faltas', 'Faltas', $this->faltas, 3, 3, false); + $this->campoNumero('carga_horaria_disciplina', 'carga_horaria_disciplina', $this->carga_horaria_disciplina, 3, 3, false, null, null, null, null, null, $habilitaCargaHoraria); + $this->campoNumero('ordenamento', 'ordenamento', $this->ordenamento, 3, 3, false); + $options = ['label' => 'Dependência', 'value' => $this->disciplinaDependencia]; $this->inputsHelper()->checkbox('disciplinaDependencia', $options); - //$this->campoOculto("sequencial",""); - $this->campoTabelaFim(); - //$this->campoOculto("ultimo_sequencial","$qtd_disciplinas"); - $this->campoQuebra(); - //---------------------FIM INCLUI DISCIPLINAS---------------------// - // carrega estilo para feedback messages, para exibir msg validação frequencia. + //---------------------FIM INCLUI DISCIPLINAS---------------------// - $style = "/modules/Portabilis/Assets/Stylesheets/Frontend.css"; - Portabilis_View_Helper_Application::loadStylesheet($this, $style); + // carrega estilo para feedback messages, para exibir msg validação frequencia. + $style = '/modules/Portabilis/Assets/Stylesheets/Frontend.css'; + Portabilis_View_Helper_Application::loadStylesheet($this, $style); Portabilis_View_Helper_Application::loadJavascript( $this, - array('/modules/Portabilis/Assets/Javascripts/Utils.js', - '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/SimpleSearch.js', - '/modules/Portabilis/Assets/Javascripts/Validator.js', - '/modules/Cadastro/Assets/Javascripts/HistoricoEscolar.js') + [ + '/modules/Portabilis/Assets/Javascripts/Utils.js', + '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/SimpleSearch.js', + '/modules/Portabilis/Assets/Javascripts/Validator.js', + '/modules/Cadastro/Assets/Javascripts/HistoricoEscolar.js' + ] ); } - function Novo() + public function Novo() { - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - $obj_permissoes = new clsPermissoes(); - $obj_permissoes->permissao_cadastra( 578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); + $obj_permissoes->permissao_cadastra(578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); + + $this->carga_horaria = str_replace('.', '', $this->carga_horaria); + $this->carga_horaria = str_replace(',', '.', $this->carga_horaria); -/* $this->historico_disciplinas = unserialize( urldecode( $this->historico_disciplinas ) ); - if ($this->historico_disciplinas) - { - */ - $this->carga_horaria = str_replace(".","",$this->carga_horaria); - $this->carga_horaria = str_replace(",",".",$this->carga_horaria); + $this->frequencia = $this->fixupFrequencia($this->frequencia); - $this->frequencia = $this->fixupFrequencia($this->frequencia); + $this->extra_curricular = is_null($this->extra_curricular) ? 0 : 1; - $this->extra_curricular = is_null($this->extra_curricular) ? 0 : 1; + $obj = new clsPmieducarHistoricoEscolar($this->ref_cod_aluno, null, null, $this->pessoa_logada, $this->nm_serie, $this->ano, $this->carga_horaria, $this->dias_letivos, $this->escola, $this->escola_cidade, $this->escola_uf, $this->observacao, $this->aprovado, null, null, 1, $this->faltas_globalizadas, $this->ref_cod_instituicao, 1, $this->extra_curricular, null, $this->frequencia, $this->registro, $this->livro, $this->folha, $this->nm_curso, $this->historico_grade_curso_id, $this->aceleracao, $this->ref_cod_escola, !is_null($this->dependencia), $this->posicao); + $cadastrou = $obj->cadastra(); - $obj = new clsPmieducarHistoricoEscolar( $this->ref_cod_aluno, null, null, $this->pessoa_logada, $this->nm_serie, $this->ano, $this->carga_horaria, $this->dias_letivos, $this->escola, $this->escola_cidade, $this->escola_uf, $this->observacao, $this->aprovado, null, null, 1, $this->faltas_globalizadas, $this->ref_cod_instituicao, 1, $this->extra_curricular, null, $this->frequencia, $this->registro, $this->livro, $this->folha, $this->nm_curso, $this->historico_grade_curso_id, $this->aceleracao, $this->ref_cod_escola, !is_null($this->dependencia), $this->posicao); - $cadastrou = $obj->cadastra(); - if( $cadastrou ) - { + if ($cadastrou) { //--------------CADASTRA DISCIPLINAS--------------// - if ($this->nm_disciplina) - { - $sequencial = 1; - foreach ( $this->nm_disciplina AS $key => $disciplina ) - { + if ($this->nm_disciplina) { + $sequencial = 1; - $obj_historico = new clsPmieducarHistoricoEscolar(); - $this->sequencial = $obj_historico->getMaxSequencial( $this->ref_cod_aluno ); + foreach ($this->nm_disciplina as $key => $disciplina) { + $obj_historico = new clsPmieducarHistoricoEscolar(); + $this->sequencial = $obj_historico->getMaxSequencial($this->ref_cod_aluno); - $obj = new clsPmieducarHistoricoDisciplinas( $sequencial, $this->ref_cod_aluno, $this->sequencial, $disciplina, $this->nota[$key], $this->faltas[$key], $this->ordenamento[$key], $this->carga_horaria_disciplina[$key], $this->disciplinaDependencia[$key] == 'on' ? true : false); - $cadastrou1 = $obj->cadastra(); - if( !$cadastrou1 ) - { - $this->mensagem = "Cadastro não realizado.
"; - echo ""; - return false; - } + $obj = new clsPmieducarHistoricoDisciplinas($sequencial, $this->ref_cod_aluno, $this->sequencial, $disciplina, $this->nota[$key], $this->faltas[$key], $this->ordenamento[$key], $this->carga_horaria_disciplina[$key], $this->disciplinaDependencia[$key] == 'on' ? true : false, $this->tipo_base[$key]); + $cadastrou1 = $obj->cadastra(); - $sequencial++; + if (!$cadastrou1) { + $this->mensagem = 'Cadastro não realizado.
'; + + return false; } - $this->mensagem .= "Cadastro efetuado com sucesso.
"; - header( "Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); - die(); - return true; + + $sequencial++; } - //--------------FIM CADASTRA DISCIPLINAS--------------// + + $this->mensagem .= 'Cadastro efetuado com sucesso.
'; + header("Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); + die(); + + return true; } - $this->mensagem = "Cadastro não realizado.
"; - echo ""; - return false; -/* } - echo ""; - $this->mensagem = "Cadastro não realizado.
"; + //--------------FIM CADASTRA DISCIPLINAS--------------// + } + $this->mensagem = 'Cadastro não realizado.
'; + return false; - */ } - function Editar() + public function Editar() { - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - $obj_permissoes = new clsPermissoes(); - $obj_permissoes->permissao_cadastra( 578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); + $obj_permissoes->permissao_cadastra(578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); $historicoEscolar = new clsPmieducarHistoricoEscolar($this->ref_cod_aluno, $this->sequencial); $historicoEscolarDetalheAntes = $historicoEscolar->detalhe(); -/* $this->historico_disciplinas = unserialize( urldecode( $this->historico_disciplinas ) ); - if ($this->historico_disciplinas) - { - */ - - $this->carga_horaria = str_replace(".","",$this->carga_horaria); - $this->carga_horaria = str_replace(",",".",$this->carga_horaria); + $this->carga_horaria = str_replace('.', '', $this->carga_horaria); + $this->carga_horaria = str_replace(',', '.', $this->carga_horaria); - $this->frequencia = $this->fixupFrequencia($this->frequencia); + $this->frequencia = $this->fixupFrequencia($this->frequencia); - if($this->cb_faltas_globalizadas != 'on') - $this->faltas_globalizadas = 'NULL'; + if ($this->cb_faltas_globalizadas != 'on') { + $this->faltas_globalizadas = 'NULL'; + } - $this->aceleracao = is_null($this->aceleracao) ? 0 : 1; - $this->extra_curricular = is_null($this->extra_curricular) ? 0 : 1; + $this->aceleracao = is_null($this->aceleracao) ? 0 : 1; + $this->extra_curricular = is_null($this->extra_curricular) ? 0 : 1; - $obj = new clsPmieducarHistoricoEscolar( $this->ref_cod_aluno, $this->sequencial, $this->pessoa_logada, null, $this->nm_serie, $this->ano, $this->carga_horaria, $this->dias_letivos, $this->escola, $this->escola_cidade, $this->escola_uf, $this->observacao, $this->aprovado, null, null, 1, $this->faltas_globalizadas, $this->ref_cod_instituicao, 1, $this->extra_curricular, null, $this->frequencia, $this->registro, $this->livro, $this->folha, $this->nm_curso, $this->historico_grade_curso_id, $this->aceleracao, $this->ref_cod_escola, !is_null($this->dependencia), $this->posicao); - $editou = $obj->edita(); + $obj = new clsPmieducarHistoricoEscolar($this->ref_cod_aluno, $this->sequencial, $this->pessoa_logada, null, $this->nm_serie, $this->ano, $this->carga_horaria, $this->dias_letivos, $this->escola, $this->escola_cidade, $this->escola_uf, $this->observacao, $this->aprovado, null, null, 1, $this->faltas_globalizadas, $this->ref_cod_instituicao, 1, $this->extra_curricular, null, $this->frequencia, $this->registro, $this->livro, $this->folha, $this->nm_curso, $this->historico_grade_curso_id, $this->aceleracao, $this->ref_cod_escola, !is_null($this->dependencia), $this->posicao); + $editou = $obj->edita(); - if( $editou ) - { + if ($editou) { //--------------EDITA DISCIPLINAS--------------// - if ($this->nm_disciplina) - { - //$this->historico_disciplinas = unserialize( urldecode( $this->historico_disciplinas ) ); - - $obj = new clsPmieducarHistoricoDisciplinas(); - $excluiu = $obj->excluirTodos( $this->ref_cod_aluno,$this->sequencial ); - if ( $excluiu ) - { - $sequencial = 1; - foreach ( $this->nm_disciplina AS $key => $disciplina ) - { - //$campo['nm_disciplina_'] = urldecode($campo['nm_disciplina_']); - - - $obj = new clsPmieducarHistoricoDisciplinas( $sequencial, $this->ref_cod_aluno, $this->sequencial, $disciplina, $this->nota[$key], $this->faltas[$key], $this->ordenamento[$key], $this->carga_horaria_disciplina[$key], $this->disciplinaDependencia[$key] == 'on' ? true : false ); - $cadastrou1 = $obj->cadastra(); - if( !$cadastrou1 ) - { - $this->mensagem = "Cadastro não realizado.
"; - echo ""; - return false; - } - $sequencial++; + if ($this->nm_disciplina) { + + $obj = new clsPmieducarHistoricoDisciplinas(); + $excluiu = $obj->excluirTodos($this->ref_cod_aluno, $this->sequencial); + if ($excluiu) { + $sequencial = 1; + foreach ($this->nm_disciplina as $key => $disciplina) { + //$campo['nm_disciplina_'] = urldecode($campo['nm_disciplina_']); + + $obj = new clsPmieducarHistoricoDisciplinas($sequencial, $this->ref_cod_aluno, $this->sequencial, $disciplina, $this->nota[$key], $this->faltas[$key], $this->ordenamento[$key], $this->carga_horaria_disciplina[$key], $this->disciplinaDependencia[$key] == 'on' ? true : false, $this->tipo_base[$key]); + $cadastrou1 = $obj->cadastra(); + if (!$cadastrou1) { + $this->mensagem = 'Cadastro não realizado.
'; + + return false; } + $sequencial++; } - $this->mensagem .= "Edição efetuada com sucesso.
"; - header( "Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); - die(); - return true; } - //--------------FIM EDITA DISCIPLINAS--------------// + $this->mensagem .= 'Edição efetuada com sucesso.
'; + header("Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); + die(); + + return true; } - $this->mensagem = "Edição não realizada.
"; - echo ""; - return false; -/* } - echo ""; - $this->mensagem = "Edição não realizada.
"; + //--------------FIM EDITA DISCIPLINAS--------------// + } + $this->mensagem = 'Edição não realizada.
'; + return false; - */ } - function Excluir() + public function Excluir() { - @session_start(); - $this->pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - $obj_permissoes = new clsPermissoes(); - $obj_permissoes->permissao_excluir( 578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); + $obj_permissoes->permissao_excluir(578, $this->pessoa_logada, 7, "educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); - - $obj = new clsPmieducarHistoricoEscolar( $this->ref_cod_aluno, $this->sequencial, $this->pessoa_logada,null,null,null,null,null,null,null,null,null,null,null,null,0 ); + $obj = new clsPmieducarHistoricoEscolar($this->ref_cod_aluno, $this->sequencial, $this->pessoa_logada, null, null, null, null, null, null, null, null, null, null, null, null, 0); $historicoEscolar = $obj->detalhe(); $excluiu = $obj->excluir(); - if( $excluiu ) - { - $obj = new clsPmieducarHistoricoDisciplinas(); - $excluiu = $obj->excluirTodos( $this->ref_cod_aluno,$this->sequencial ); - if ( $excluiu ) - { - $this->mensagem .= "Exclusão efetuada com sucesso.
"; - header( "Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}" ); + if ($excluiu) { + $obj = new clsPmieducarHistoricoDisciplinas(); + $excluiu = $obj->excluirTodos($this->ref_cod_aluno, $this->sequencial); + if ($excluiu) { + $this->mensagem .= 'Exclusão efetuada com sucesso.
'; + header("Location: educar_historico_escolar_lst.php?ref_cod_aluno={$this->ref_cod_aluno}"); die(); + return true; } } - $this->mensagem = "Exclusão não realizada.
"; - echo ""; + $this->mensagem = 'Exclusão não realizada.
'; + return false; } - protected function fixupFrequencia($frequencia) { + protected function fixupFrequencia($frequencia) + { if (strpos($frequencia, ',')) { - $frequencia = str_replace('.', '', $frequencia); + $frequencia = str_replace('.', '', $frequencia); $frequencia = str_replace(',', '.', $frequencia); } return $frequencia; } - function habilitaCargaHoraria($instituicao) + + public function habilitaCargaHoraria($instituicao) { $obj_instituicao = new clsPmieducarInstituicao($instituicao); $detalhe_instituicao = $obj_instituicao->detalhe(); @@ -568,37 +519,32 @@ function habilitaCargaHoraria($instituicao) } } - -function getOpcoesGradeCurso(){ - - $db = new clsBanco(); - $sql = "select * from pmieducar.historico_grade_curso where ativo = 1"; - $db->Consulta($sql); - - $opcoes = array("" => "Selecione"); - while ($db->ProximoRegistro()){ - $record = $db->Tupla(); - $opcoes[$record['id']] = $record['descricao_etapa']; - } - - return $opcoes; +function getOpcoesGradeCurso() +{ + $db = new clsBanco(); + $sql = 'select * from pmieducar.historico_grade_curso where ativo = 1'; + $db->Consulta($sql); + + $opcoes = ['' => 'Selecione']; + while ($db->ProximoRegistro()) { + $record = $db->Tupla(); + $opcoes[$record['id']] = $record['descricao_etapa']; } - function validaControlePosicaoHistorico(){ + return $opcoes; +} + +function validaControlePosicaoHistorico() +{ $obj = new clsPmieducarInstituicao; //Busca instituicao ativa - $lst = $obj->lista(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1); + $lst = $obj->lista(null, null, null, null, null, null, null, null, null, null, null, null, null, 1); return dbBool($lst[0]['controlar_posicao_historicos']); - } - +} -// cria uma extensao da classe base $pagina = new clsIndexBase(); -// cria o conteudo $miolo = new indice(); -// adiciona o conteudo na clsBase -$pagina->addForm( $miolo ); -// gera o html + +$pagina->addForm($miolo); $pagina->MakeAll(); -?> diff --git a/ieducar/intranet/educar_matricula_turma_cad.php b/ieducar/intranet/educar_matricula_turma_cad.php index ba64b6d4b1..088fc5a56d 100644 --- a/ieducar/intranet/educar_matricula_turma_cad.php +++ b/ieducar/intranet/educar_matricula_turma_cad.php @@ -165,7 +165,7 @@ function novaEnturmacao($matriculaId, $turmaDestinoId) { 1); $enturmacao->data_enturmacao = $this->data_enturmacao; - + $this->atualizaUltimaEnturmacao($matriculaId); return $enturmacao->cadastra(); } return false; @@ -259,6 +259,35 @@ function getSequencialEnturmacaoByTurmaId($matriculaId, $turmaId) { return 1; } + function atualizaUltimaEnturmacao($matriculaId) + { + $objMatriculaTurma = new clsPmieducarMatriculaTurma(); + $ultima_turma = $objMatriculaTurma->getUltimaTurmaEnturmacao($matriculaId); + $sequencial = $objMatriculaTurma->getMaxSequencialEnturmacao($matriculaId); + $lst_ativo = $objMatriculaTurma->lista($matriculaId, $ultima_turma, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $sequencial); + $ativo = $lst_ativo[0]['ativo']; + if ($sequencial >= 1) { + $remanejado = TRUE; + $enturmacao = new clsPmieducarMatriculaTurma( + $matriculaId, + $ultima_turma, + $this->pessoa_logada, + $this->pessoa_logada, + NULL, + NULL, + $ativo, + NULL, + $sequencial, + NULL, + NULL, + NULL, + $remanejado); + return $enturmacao->edita(); + } + return false; + } + + function Gerar() { @@ -288,4 +317,4 @@ function Excluir() $pagina->addForm($miolo); // Gera o código HTML -$pagina->MakeAll(); +$pagina->MakeAll(); \ No newline at end of file diff --git a/ieducar/intranet/educar_turma_cad.php b/ieducar/intranet/educar_turma_cad.php index 21feee904c..8efe99023e 100644 --- a/ieducar/intranet/educar_turma_cad.php +++ b/ieducar/intranet/educar_turma_cad.php @@ -857,13 +857,6 @@ function Editar() $objTurma = $this->montaObjetoTurma($this->cod_turma, null, $this->pessoa_logada); $editou = $objTurma->edita(); - // Caso tenham sido selecionadas discplinas, como se trata de uma edição de turma será rodado uma consulta - // que limpa os Componentes Curriculares antigos. - if ($this->disciplinas != 1) { - $anoLetivo = $this->ano ? $this->ano : date("Y"); - CleanComponentesCurriculares::destroyOldResources($anoLetivo); - } - if (!$editou) { $this->mensagem = 'Edição não realizada.'; echo ""; diff --git a/ieducar/intranet/include/pmieducar/clsPmieducarHistoricoDisciplinas.inc.php b/ieducar/intranet/include/pmieducar/clsPmieducarHistoricoDisciplinas.inc.php index 6688e33f9e..53ee6a162e 100644 --- a/ieducar/intranet/include/pmieducar/clsPmieducarHistoricoDisciplinas.inc.php +++ b/ieducar/intranet/include/pmieducar/clsPmieducarHistoricoDisciplinas.inc.php @@ -1,260 +1,251 @@ _schema = "pmieducar."; - $this->_tabela = "{$this->_schema}historico_disciplinas"; - $this->_campos_lista = $this->_todos_campos = "sequencial, ref_ref_cod_aluno, ref_sequencial, nm_disciplina, nota, faltas, ordenamento, carga_horaria_disciplina, dependencia"; - - if( is_numeric( $ref_ref_cod_aluno ) && is_numeric( $ref_sequencial ) ) - { - if( class_exists( "clsPmieducarHistoricoEscolar" ) ) - { - $tmp_obj = new clsPmieducarHistoricoEscolar( $ref_ref_cod_aluno, $ref_sequencial ); - if( method_exists( $tmp_obj, "existe") ) - { - if( $tmp_obj->existe() ) - { + $this->_schema = 'pmieducar.'; + $this->_tabela = "{$this->_schema}historico_disciplinas"; + $this->_campos_lista = $this->_todos_campos = implode(', ', [ + 'sequencial', + 'ref_ref_cod_aluno', + 'ref_sequencial', + 'nm_disciplina', + 'nota', + 'faltas', + 'ordenamento', + 'carga_horaria_disciplina', + 'dependencia', + 'tipo_base', + ]); + + if (is_numeric($ref_ref_cod_aluno) && is_numeric($ref_sequencial)) { + if (class_exists('clsPmieducarHistoricoEscolar')) { + $tmp_obj = new clsPmieducarHistoricoEscolar($ref_ref_cod_aluno, $ref_sequencial); + if (method_exists($tmp_obj, 'existe')) { + if ($tmp_obj->existe()) { $this->ref_ref_cod_aluno = $ref_ref_cod_aluno; $this->ref_sequencial = $ref_sequencial; } - } - else if( method_exists( $tmp_obj, "detalhe") ) - { - if( $tmp_obj->detalhe() ) - { + } elseif (method_exists($tmp_obj, 'detalhe')) { + if ($tmp_obj->detalhe()) { $this->ref_ref_cod_aluno = $ref_ref_cod_aluno; $this->ref_sequencial = $ref_sequencial; } } - } - else - { - if( $db->CampoUnico( "SELECT 1 FROM pmieducar.historico_escolar WHERE ref_cod_aluno = '{$ref_ref_cod_aluno}' AND sequencial = '{$ref_sequencial}'" ) ) - { + } else { + if ($db->CampoUnico("SELECT 1 FROM pmieducar.historico_escolar WHERE ref_cod_aluno = '{$ref_ref_cod_aluno}' AND sequencial = '{$ref_sequencial}'")) { $this->ref_ref_cod_aluno = $ref_ref_cod_aluno; $this->ref_sequencial = $ref_sequencial; } } } - - if( is_numeric( $sequencial ) ) - { + if (is_numeric($sequencial)) { $this->sequencial = $sequencial; } - if( is_string( $nm_disciplina ) ) - { + + if (is_string($nm_disciplina)) { $this->nm_disciplina = $nm_disciplina; } - if( is_string( $nota ) ) - { + + if (is_string($nota)) { $this->nota = $nota; } - if( is_numeric( $faltas ) ) - { + + if (is_numeric($faltas)) { $this->faltas = $faltas; } - if( is_numeric( $ordenamento ) ) - { + + if (is_numeric($ordenamento)) { $this->ordenamento = $ordenamento; } - if( is_numeric( $carga_horaria_disciplina ) ) - { + + if (is_numeric($carga_horaria_disciplina)) { $this->carga_horaria_disciplina = $carga_horaria_disciplina; } + if (is_bool($dependencia)) { $this->dependencia = $dependencia; } + + if (is_numeric($tipo_base)) { + $this->tipo_base = $tipo_base; + } } /** * Cria um novo registro * * @return bool + * + * @throws Exception */ - function cadastra() + public function cadastra() { - if( is_numeric( $this->ref_ref_cod_aluno ) && is_numeric( $this->ref_sequencial ) && is_string( $this->nm_disciplina ) && is_string( $this->nota ) ) - { + if (is_numeric($this->ref_ref_cod_aluno) && is_numeric($this->ref_sequencial) && is_string($this->nm_disciplina) && is_string($this->nota)) { $db = new clsBanco(); - $campos = ""; - $valores = ""; - $gruda = ""; - - /*if( is_numeric( $this->sequencial ) ) - { - $campos .= "{$gruda}sequencial"; - $valores .= "{$gruda}'{$this->sequencial}'"; - $gruda = ", "; - }*/ - if( is_numeric( $this->ref_ref_cod_aluno ) ) - { + $campos = ''; + $valores = ''; + $gruda = ''; + + if (is_numeric($this->ref_ref_cod_aluno)) { $campos .= "{$gruda}ref_ref_cod_aluno"; $valores .= "{$gruda}'{$this->ref_ref_cod_aluno}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_numeric( $this->ref_sequencial ) ) - { + + if (is_numeric($this->ref_sequencial)) { $campos .= "{$gruda}ref_sequencial"; $valores .= "{$gruda}'{$this->ref_sequencial}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_string( $this->nm_disciplina ) ) - { + + if (is_string($this->nm_disciplina)) { $campos .= "{$gruda}nm_disciplina"; $valores .= "{$gruda}'{$this->nm_disciplina}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_string( $this->nota ) ) - { + + if (is_string($this->nota)) { $campos .= "{$gruda}nota"; $valores .= "{$gruda}'{$this->nota}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_numeric( $this->faltas ) ) - { + + if (is_numeric($this->faltas)) { $campos .= "{$gruda}faltas"; $valores .= "{$gruda}'{$this->faltas}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_numeric( $this->ordenamento ) ) - { + + if (is_numeric($this->ordenamento)) { $campos .= "{$gruda}ordenamento"; $valores .= "{$gruda}'{$this->ordenamento}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_numeric( $this->carga_horaria_disciplina ) ) - { + + if (is_numeric($this->carga_horaria_disciplina)) { $campos .= "{$gruda}carga_horaria_disciplina"; $valores .= "{$gruda}'{$this->carga_horaria_disciplina}'"; - $gruda = ", "; + $gruda = ', '; } - if($this->dependencia) - { + + if ($this->dependencia) { $campos .= "{$gruda}dependencia"; - $valores .= "{$gruda}TRUE"; - $gruda = ", "; + $valores .= "{$gruda}true"; + $gruda = ', '; + } + + if ($this->tipo_base) { + $campos .= "{$gruda}tipo_base"; + $valores .= "{$gruda}{$this->tipo_base}"; + $gruda = ', '; } - $sequencial = $db->campoUnico("SELECT COALESCE( MAX(sequencial), 0 ) + 1 FROM {$this->_tabela} WHERE ref_ref_cod_aluno = {$this->ref_ref_cod_aluno} AND ref_sequencial = {$this->ref_sequencial}" ); + $sequencial = $db->campoUnico("SELECT COALESCE( MAX(sequencial), 0 ) + 1 FROM {$this->_tabela} WHERE ref_ref_cod_aluno = {$this->ref_ref_cod_aluno} AND ref_sequencial = {$this->ref_sequencial}"); - $db->Consulta( "INSERT INTO {$this->_tabela} ( sequencial, $campos ) VALUES( $sequencial, $valores )" ); + $db->Consulta("INSERT INTO {$this->_tabela} ( sequencial, $campos ) VALUES( $sequencial, $valores )"); -// $db->Consulta( "INSERT INTO {$this->_tabela} ( $campos ) VALUES( $valores )" ); return true; } + return false; } @@ -262,52 +253,58 @@ function cadastra() * Edita os dados de um registro * * @return bool + * + * @throws Exception */ - function edita() + public function edita() { - if( is_numeric( $this->sequencial ) && is_numeric( $this->ref_ref_cod_aluno ) && is_numeric( $this->ref_sequencial ) ) - { - + if (is_numeric($this->sequencial) && is_numeric($this->ref_ref_cod_aluno) && is_numeric($this->ref_sequencial)) { $db = new clsBanco(); - $set = ""; + $set = ''; + $gruda = ''; - if( is_string( $this->nm_disciplina ) ) - { + if (is_string($this->nm_disciplina)) { $set .= "{$gruda}nm_disciplina = '{$this->nm_disciplina}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_string( $this->nota ) ) - { + + if (is_string($this->nota)) { $set .= "{$gruda}nota = '{$this->nota}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_numeric( $this->faltas ) ) - { + + if (is_numeric($this->faltas)) { $set .= "{$gruda}faltas = '{$this->faltas}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_numeric( $this->ordenamento ) ) - { + + if (is_numeric($this->ordenamento)) { $set .= "{$gruda}ordenamento = '{$this->ordenamento}'"; - $gruda = ", "; + $gruda = ', '; } - if( is_numeric( $this->carga_horaria_disciplina ) ) - { + + if (is_numeric($this->carga_horaria_disciplina)) { $set .= "{$gruda}carga_horaria_disciplina = '{$this->carga_horaria_disciplina}'"; - $gruda = ", "; + $gruda = ', '; } - if($this->dependencia) - { + + if ($this->dependencia) { $set .= "{$gruda}dependencia = TRUE"; - $gruda = ", "; + $gruda = ', '; } - if( $set ) - { - $db->Consulta( "UPDATE {$this->_tabela} SET $set WHERE sequencial = '{$this->sequencial}' AND ref_ref_cod_aluno = '{$this->ref_ref_cod_aluno}' AND ref_sequencial = '{$this->ref_sequencial}'" ); + if ($this->dependencia) { + $set .= "{$gruda}tipo_base = {$this->tipo_base}"; + $gruda = ', '; + } + + if ($set) { + $db->Consulta("UPDATE {$this->_tabela} SET $set WHERE sequencial = '{$this->sequencial}' AND ref_ref_cod_aluno = '{$this->ref_ref_cod_aluno}' AND ref_sequencial = '{$this->ref_sequencial}'"); + return true; } } + return false; } @@ -315,92 +312,89 @@ function edita() * Retorna uma lista filtrados de acordo com os parametros * * @return array + * + * @throws Exception */ - function lista( $int_sequencial = null, $int_ref_ref_cod_aluno = null, $int_ref_sequencial = null, $str_nm_disciplina = null, $str_nota = null, $int_faltas = null, $int_ordenamento = null, $int_carga_horaria_disciplina = null, $bool_dependencia = false) + public function lista($int_sequencial = null, $int_ref_ref_cod_aluno = null, $int_ref_sequencial = null, $str_nm_disciplina = null, $str_nota = null, $int_faltas = null, $int_ordenamento = null, $int_carga_horaria_disciplina = null, $bool_dependencia = false) { $sql = "SELECT {$this->_campos_lista} FROM {$this->_tabela}"; - $filtros = ""; + $filtros = ''; - $whereAnd = " WHERE "; + $whereAnd = ' WHERE '; - if( is_numeric( $int_sequencial ) ) - { + if (is_numeric($int_sequencial)) { $filtros .= "{$whereAnd} sequencial = '{$int_sequencial}'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if( is_numeric( $int_ref_ref_cod_aluno ) ) - { + + if (is_numeric($int_ref_ref_cod_aluno)) { $filtros .= "{$whereAnd} ref_ref_cod_aluno = '{$int_ref_ref_cod_aluno}'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if( is_numeric( $int_ref_sequencial ) ) - { + + if (is_numeric($int_ref_sequencial)) { $filtros .= "{$whereAnd} ref_sequencial = '{$int_ref_sequencial}'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if( is_string( $str_nm_disciplina ) ) - { + + if (is_string($str_nm_disciplina)) { $filtros .= "{$whereAnd} nm_disciplina LIKE '%{$str_nm_disciplina}%'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if( is_string( $str_nota ) ) - { + + if (is_string($str_nota)) { $filtros .= "{$whereAnd} nota LIKE '%{$str_nota}%'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if( is_numeric( $int_faltas ) ) - { + + if (is_numeric($int_faltas)) { $filtros .= "{$whereAnd} faltas = '{$int_faltas}'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if( is_numeric( $int_ordenamento ) ) - { + + if (is_numeric($int_ordenamento)) { $filtros .= "{$whereAnd} ordenamento = '{$int_ordenamento}'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if( is_numeric( $int_carga_horaria_disciplina ) ) - { + + if (is_numeric($int_carga_horaria_disciplina)) { $filtros .= "{$whereAnd} carga_horaria_disciplina = '{$int_carga_horaria_disciplina}'"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } - if($bool_dependencia) - { + + if ($bool_dependencia) { $filtros .= "{$whereAnd} dependencia = TRUE"; - $whereAnd = " AND "; + $whereAnd = ' AND '; } $db = new clsBanco(); - $countCampos = count( explode( ",", $this->_campos_lista ) ); - $resultado = array(); + $countCampos = count(explode(',', $this->_campos_lista)); + $resultado = []; $sql .= $filtros . $this->getOrderby() . $this->getLimite(); - $this->_total = $db->CampoUnico( "SELECT COUNT(0) FROM {$this->_tabela} {$filtros}" ); + $this->_total = $db->CampoUnico("SELECT COUNT(0) FROM {$this->_tabela} {$filtros}"); - $db->Consulta( $sql ); + $db->Consulta($sql); - if( $countCampos > 1 ) - { - while ( $db->ProximoRegistro() ) - { + if ($countCampos > 1) { + while ($db->ProximoRegistro()) { $tupla = $db->Tupla(); - $tupla["_total"] = $this->_total; + $tupla['_total'] = $this->_total; $resultado[] = $tupla; } - } - else - { - while ( $db->ProximoRegistro() ) - { + } else { + while ($db->ProximoRegistro()) { $tupla = $db->Tupla(); $resultado[] = $tupla[$this->_campos_lista]; } } - if( count( $resultado ) ) - { + + if (count($resultado)) { return $resultado; } + return false; } @@ -408,17 +402,19 @@ function lista( $int_sequencial = null, $int_ref_ref_cod_aluno = null, $int_ref_ * Retorna um array com os dados de um registro * * @return array + * + * @throws Exception */ - function detalhe() + public function detalhe() { - if( is_numeric( $this->sequencial ) && is_numeric( $this->ref_ref_cod_aluno ) && is_numeric( $this->ref_sequencial ) ) - { + if (is_numeric($this->sequencial) && is_numeric($this->ref_ref_cod_aluno) && is_numeric($this->ref_sequencial)) { + $db = new clsBanco(); + $db->Consulta("SELECT {$this->_todos_campos} FROM {$this->_tabela} WHERE sequencial = '{$this->sequencial}' AND ref_ref_cod_aluno = '{$this->ref_ref_cod_aluno}' AND ref_sequencial = '{$this->ref_sequencial}'"); + $db->ProximoRegistro(); - $db = new clsBanco(); - $db->Consulta( "SELECT {$this->_todos_campos} FROM {$this->_tabela} WHERE sequencial = '{$this->sequencial}' AND ref_ref_cod_aluno = '{$this->ref_ref_cod_aluno}' AND ref_sequencial = '{$this->ref_sequencial}'" ); - $db->ProximoRegistro(); - return $db->Tupla(); + return $db->Tupla(); } + return false; } @@ -426,17 +422,19 @@ function detalhe() * Retorna um array com os dados de um registro * * @return array + * + * @throws Exception */ - function existe() + public function existe() { - if( is_numeric( $this->sequencial ) && is_numeric( $this->ref_ref_cod_aluno ) && is_numeric( $this->ref_sequencial ) ) - { + if (is_numeric($this->sequencial) && is_numeric($this->ref_ref_cod_aluno) && is_numeric($this->ref_sequencial)) { + $db = new clsBanco(); + $db->Consulta("SELECT 1 FROM {$this->_tabela} WHERE sequencial = '{$this->sequencial}' AND ref_ref_cod_aluno = '{$this->ref_ref_cod_aluno}' AND ref_sequencial = '{$this->ref_sequencial}'"); + $db->ProximoRegistro(); - $db = new clsBanco(); - $db->Consulta( "SELECT 1 FROM {$this->_tabela} WHERE sequencial = '{$this->sequencial}' AND ref_ref_cod_aluno = '{$this->ref_ref_cod_aluno}' AND ref_sequencial = '{$this->ref_sequencial}'" ); - $db->ProximoRegistro(); - return $db->Tupla(); + return $db->Tupla(); } + return false; } @@ -445,33 +443,23 @@ function existe() * * @return bool */ - function excluir() + public function excluir() { - if( is_numeric( $this->sequencial ) && is_numeric( $this->ref_ref_cod_aluno ) && is_numeric( $this->ref_sequencial ) ) - { - - /* - delete - $db = new clsBanco(); - $db->Consulta( "DELETE FROM {$this->_tabela} WHERE sequencial = '{$this->sequencial}' AND ref_ref_cod_aluno = '{$this->ref_ref_cod_aluno}' AND ref_sequencial = '{$this->ref_sequencial}'" ); - return true; - */ - - - } return false; } /** * Exclui todos os registros referentes a um historico do aluno */ - function excluirTodos( $ref_cod_aluno, $ref_sequencial ) + public function excluirTodos($ref_cod_aluno, $ref_sequencial) { - if ( is_numeric( $ref_cod_aluno ) && is_numeric( $ref_sequencial ) ) { + if (is_numeric($ref_cod_aluno) && is_numeric($ref_sequencial)) { $db = new clsBanco(); - $db->Consulta( "DELETE FROM {$this->_tabela} WHERE ref_ref_cod_aluno = '{$ref_cod_aluno}' AND ref_sequencial = '{$ref_sequencial}'" ); + $db->Consulta("DELETE FROM {$this->_tabela} WHERE ref_ref_cod_aluno = '{$ref_cod_aluno}' AND ref_sequencial = '{$ref_sequencial}'"); + return true; } + return false; } @@ -480,7 +468,7 @@ function excluirTodos( $ref_cod_aluno, $ref_sequencial ) * * @return null */ - function setCamposLista( $str_campos ) + public function setCamposLista($str_campos) { $this->_campos_lista = $str_campos; } @@ -490,7 +478,7 @@ function setCamposLista( $str_campos ) * * @return null */ - function resetCamposLista() + public function resetCamposLista() { $this->_campos_lista = $this->_todos_campos; } @@ -500,7 +488,7 @@ function resetCamposLista() * * @return null */ - function setLimite( $intLimiteQtd, $intLimiteOffset = null ) + public function setLimite($intLimiteQtd, $intLimiteOffset = null) { $this->_limite_quantidade = $intLimiteQtd; $this->_limite_offset = $intLimiteOffset; @@ -511,18 +499,18 @@ function setLimite( $intLimiteQtd, $intLimiteOffset = null ) * * @return string */ - function getLimite() + public function getLimite() { - if( is_numeric( $this->_limite_quantidade ) ) - { + if (is_numeric($this->_limite_quantidade)) { $retorno = " LIMIT {$this->_limite_quantidade}"; - if( is_numeric( $this->_limite_offset ) ) - { + if (is_numeric($this->_limite_offset)) { $retorno .= " OFFSET {$this->_limite_offset} "; } + return $retorno; } - return ""; + + return ''; } /** @@ -530,13 +518,9 @@ function getLimite() * * @return null */ - function setOrderby( $strNomeCampo ) + public function setOrderby($strNomeCampo) { - // limpa a string de possiveis erros (delete, insert, etc) - //$strNomeCampo = eregi_replace(); - - if( is_string( $strNomeCampo ) && $strNomeCampo ) - { + if (is_string($strNomeCampo) && $strNomeCampo) { $this->_campo_order_by = $strNomeCampo; } } @@ -546,25 +530,24 @@ function setOrderby( $strNomeCampo ) * * @return string */ - function getOrderby() + public function getOrderby() { - if( is_string( $this->_campo_order_by ) ) - { + if (is_string($this->_campo_order_by)) { return " ORDER BY {$this->_campo_order_by} "; } - return ""; + + return ''; } - function getMaxSequencial( $ref_cod_aluno ) + public function getMaxSequencial($ref_cod_aluno) { - if( is_numeric( $ref_cod_aluno ) ) - { + if (is_numeric($ref_cod_aluno)) { $db = new clsBanco(); - $sequencial = $db->campoUnico("SELECT COALESCE( MAX(sequencial), 0 ) FROM {$this->_tabela} WHERE ref_cod_aluno = {$ref_cod_aluno}" ); + $sequencial = $db->campoUnico("SELECT COALESCE( MAX(sequencial), 0 ) FROM {$this->_tabela} WHERE ref_cod_aluno = {$ref_cod_aluno}"); + return $sequencial; } + return false; } - } -?> \ No newline at end of file diff --git a/ieducar/intranet/include/pmieducar/clsPmieducarMatriculaTurma.inc.php b/ieducar/intranet/include/pmieducar/clsPmieducarMatriculaTurma.inc.php index c79d50c0dd..fc30275545 100644 --- a/ieducar/intranet/include/pmieducar/clsPmieducarMatriculaTurma.inc.php +++ b/ieducar/intranet/include/pmieducar/clsPmieducarMatriculaTurma.inc.php @@ -61,6 +61,7 @@ class clsPmieducarMatriculaTurma var $reabrirMatricula; var $etapa_educacenso; var $turma_unificada; + var $remanejado; /** * Armazena o total de resultados obtidos na última chamada ao método lista(). @@ -119,7 +120,7 @@ function __construct($ref_cod_matricula = NULL, $ref_cod_turma = NULL, $ref_usuario_exc = NULL, $ref_usuario_cad = NULL, $data_cadastro = NULL, $data_exclusao = NULL, $ativo = NULL, $ref_cod_turma_transf = NULL,$sequencial = NULL, $data_enturmacao = NULL, - $removerSequencial = FALSE, $reabrirMatricula = FALSE + $removerSequencial = FALSE, $reabrirMatricula = FALSE, $remanejado = FALSE ) { $db = new clsBanco(); $this->_schema = "pmieducar."; @@ -228,6 +229,10 @@ function __construct($ref_cod_matricula = NULL, $this->ativo = $ativo; } + if ($remanejado) { + $this->remanejado = $remanejado; + } + if (is_numeric($ref_cod_turma_transf)) { if (class_exists("clsPmieducarTurma")) { $tmp_obj = new clsPmieducarTurma($ref_cod_turma_transf); @@ -338,8 +343,6 @@ function cadastra() $auditoria = new clsModulesAuditoriaGeral("matricula_turma", $this->pessoa_logada, $this->ref_cod_matricula); $auditoria->inclusao($detalhe); - $this->limpaComponentesCurriculares(); - return TRUE; } @@ -401,6 +404,13 @@ function edita() } } + if (! $this->ativo) { + if ($this->remanejado) { + $set .= "{$gruda}remanejado = true"; + $gruda = ", "; + } + } + if (is_numeric($this->ref_cod_turma_transf)) { $set .= "{$gruda}ref_cod_turma= '{$this->ref_cod_turma_transf}'"; $gruda = ", "; @@ -434,7 +444,7 @@ function edita() $auditoria = new clsModulesAuditoriaGeral("matricula_turma", $this->pessoa_logada, $this->ref_cod_matricula); $auditoria->alteracao($detalheAntigo, $this->detalhe()); - $this->limpaComponentesCurriculares(); + return TRUE; } } @@ -1665,11 +1675,6 @@ function reclassificacao($data = null) return FALSE; } - function limpaComponentesCurriculares(){ - $ano = $this->getAnoMatricula(); - CleanComponentesCurriculares::destroyOldResources($ano, $this->ref_cod_matricula); - } - function getAnoMatricula(){ if (is_numeric($this->ref_cod_matricula)){ $db = new clsBanco(); @@ -1702,4 +1707,31 @@ function verficaEnturmacaoDeDependencia($matriculaId, $turmaId){ return $db->Tupla(); } + function getMaxSequencialEnturmacao($matriculaId) + { + $db = new clsBanco(); + $sql = 'select max(sequencial) from pmieducar.matricula_turma where ref_cod_matricula = $1'; + + if ($db->execPreparedQuery($sql, $matriculaId) != false) { + $db->ProximoRegistro(); + $sequencial = $db->Tupla(); + return $sequencial[0]; + } + return 0; + } + + function getUltimaTurmaEnturmacao($matriculaId) + { + $sequencial = $this->getMaxSequencialEnturmacao($matriculaId); + $db = new clsBanco(); + $sql = 'select ref_cod_turma from pmieducar.matricula_turma where ref_cod_matricula = $1 and sequencial = $2'; + + if ($db->execPreparedQuery($sql, [$matriculaId, $sequencial]) != false) { + $db->ProximoRegistro(); + $ultima_turma = $db->Tupla(); + return $ultima_turma[0]; + } + return NULL; + } + } diff --git a/ieducar/intranet/include/pmieducar/clsPmieducarTurmaModulo.inc.php b/ieducar/intranet/include/pmieducar/clsPmieducarTurmaModulo.inc.php index de4b6f4e3c..d613b9224d 100644 --- a/ieducar/intranet/include/pmieducar/clsPmieducarTurmaModulo.inc.php +++ b/ieducar/intranet/include/pmieducar/clsPmieducarTurmaModulo.inc.php @@ -41,6 +41,8 @@ class clsPmieducarTurmaModulo var $data_fim; var $dias_letivos; + var $pessoa_logada; + // propriedades padrao /** @@ -110,6 +112,7 @@ function __construct( $ref_cod_turma = null, $ref_cod_modulo = null, $sequencial $db = new clsBanco(); $this->_schema = "pmieducar."; $this->_tabela = "{$this->_schema}turma_modulo"; + $this->pessoa_logada = $_SESSION['id_pessoa']; $this->_campos_lista = $this->_todos_campos = "ref_cod_turma, ref_cod_modulo, sequencial, data_inicio, data_fim, dias_letivos"; @@ -448,6 +451,80 @@ function excluirTodos( $ref_cod_turma = null ) } return false; } + + public function removeStepsOfClassesForCourseAndYear($courseCode, $year) + { + if (!is_numeric($courseCode) || !is_numeric($year)) { + return false; + } + + $sql = " + DELETE FROM {$this->_tabela} + WHERE ref_cod_turma IN ( + SELECT cod_turma FROM pmieducar.turma + WHERE ref_cod_curso = {$courseCode} + AND ano = {$year} + ) RETURNING *; + "; + + try { + $db = new clsBanco(); + $db->Consulta($sql); + while ($db->ProximoRegistro()) { + $tupla[] = $db->Tupla(); + } + $this->auditStepsOfClasses($tupla, clsModulesAuditoriaGeral::OPERACAO_EXCLUSAO); + } catch (Throwable $throwable) { + return false; + } + + return true; + } + + public function copySchoolStepsIntoClassesForCourseAndYear($courseCode, $year) + { + if (!is_numeric($courseCode) || !is_numeric($year)) { + return false; + } + + $sql = " + INSERT INTO pmieducar.turma_modulo + SELECT cod_turma, ref_cod_modulo, sequencial, data_inicio, data_fim, dias_letivos + FROM pmieducar.turma + INNER JOIN pmieducar.ano_letivo_modulo ON (turma.ref_ref_cod_escola = ano_letivo_modulo.ref_ref_cod_escola + AND turma.ano = ano_letivo_modulo.ref_ano) + WHERE ref_cod_curso = {$courseCode} AND ano = {$year} + RETURNING *; + "; + + try { + $db = new clsBanco(); + $db->Consulta($sql); + while ($db->ProximoRegistro()) { + $tupla[] = $db->Tupla(); + } + $this->auditStepsOfClasses($tupla, clsModulesAuditoriaGeral::OPERACAO_INCLUSAO); + } catch (Throwable $throwable) { + return false; + } + + return true; + } + + private function auditStepsOfClasses($infos, $operation) + { + foreach ($infos as $key => $info) { + $auditoria = new clsModulesAuditoriaGeral('turma_modulo', $this->pessoa_logada, $info['ref_cod_turma']); + if ($operation == clsModulesAuditoriaGeral::OPERACAO_INCLUSAO) { + $auditoria->inclusao($info); + continue; + } + if ($operation == clsModulesAuditoriaGeral::OPERACAO_EXCLUSAO) { + $auditoria->exclusao($info); + continue; + } + } + } /** * Define quais campos da tabela serao selecionados na invocacao do metodo lista diff --git a/ieducar/intranet/scripts/calendario.js b/ieducar/intranet/scripts/calendario.js index 2486689cf4..225343fbab 100644 --- a/ieducar/intranet/scripts/calendario.js +++ b/ieducar/intranet/scripts/calendario.js @@ -77,35 +77,6 @@ else { objCSS.type = 'text/css'; } -function init() -{ - var div_calendario = document.getElementById('d_calendario'); - - if (! div_calendario) { - return; - } - - // Internet Explorer: - if (document.all) { - div_calendario.onselectstart = function () { return false; }; - } - - // Netscape 4: - if (document.layers) { - document.captureEvents(Event.MOUSEDOWN); - div_calendario.onmousedown = function (evt) { - return false; - }; - } - - // Netscape 6: - div_calendario.onmousedown = function () { - return false; - }; -} - -window.onload = init; - var cX = 0; var cY = 0; diff --git a/ieducar/intranet/scripts/etapas.js b/ieducar/intranet/scripts/etapas.js index fa6ca1746f..16a07e6dfd 100644 --- a/ieducar/intranet/scripts/etapas.js +++ b/ieducar/intranet/scripts/etapas.js @@ -42,48 +42,49 @@ $j(function () { var that = this; $j('#btn_enviar').click(function (e) { - if (parseInt($j('#padrao_ano_escolar').val(), 10) === 1) { - window.acao(); - - return; - } + if (validationUtils.validatesFields(true)) { + if (parseInt($j('#padrao_ano_escolar').val(), 10) === 1) { + window.acao(); - e.preventDefault(); + return; + } - that.resetErrors(); + e.preventDefault(); - if (!that.validateDates()) { - alert('Ocorreram erros na validação dos campos. Verifique as mensagens e tente novamente.'); + that.resetErrors(); - return false; - } + if (!that.validateDates()) { + alert('Ocorreram erros na validação dos campos. Verifique as mensagens e tente novamente.'); - var validations = [ - 'validateStartDates', - 'validateEndDates' - ]; + return false; + } - var valid = true; + var validations = [ + 'validateStartDates', + 'validateEndDates' + ]; - $j.each(validations, function (i, validation) { - if (!that[validation]()) { - valid = false; - } - }); + var valid = true; - if (valid) { - if (typeof window.valida !== "undefined") { - // reproduzindo função encontrada em modules/Cadastro/Assets/Javascripts/Turma.js:332 - if (validationUtils.validatesFields(true)) { - window.valida(); + $j.each(validations, function (i, validation) { + if (!that[validation]()) { + valid = false; + } + }); + + if (valid) { + if (typeof window.valida !== "undefined") { + // reproduzindo função encontrada em modules/Cadastro/Assets/Javascripts/Turma.js:332 + if (validationUtils.validatesFields(true)) { + window.valida(); + } + } else { + window.acao(); } } else { - window.acao(); + alert('Ocorreram erros na validação dos campos. Verifique as mensagens e tente novamente.'); } - } else { - alert('Ocorreram erros na validação dos campos. Verifique as mensagens e tente novamente.'); } - return false; }); }, diff --git a/ieducar/lib/App/Date/Exception.php b/ieducar/lib/App/Date/Exception.php index ea277a823b..fbf3daa922 100644 --- a/ieducar/lib/App/Date/Exception.php +++ b/ieducar/lib/App/Date/Exception.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Date - * @since Arquivo disponível desde a versão 1.2.0 - * @version $Id$ - */ - require_once 'CoreExt/Exception.php'; -/** - * App_Date_Exception class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Date - * @since Classe disponível desde a versão 1.2.0 - * @version @@package_version@@ - */ class App_Date_Exception extends CoreExt_Exception { -} \ No newline at end of file +} diff --git a/ieducar/lib/App/Date/Utils.php b/ieducar/lib/App/Date/Utils.php index 851d460cb8..b02fdeac1d 100644 --- a/ieducar/lib/App/Date/Utils.php +++ b/ieducar/lib/App/Date/Utils.php @@ -1,92 +1,60 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Date - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'App/Date/Exception.php'; -/** - * App_Date_Utils class. - * - * Possui métodos - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Date - * @since Classe disponível desde a versão 1.2.0 - * @version @@package_version@@ - */ class App_Date_Utils { - /** - * Retorna o ano de uma string nos formatos dd/mm/yyyy e dd/mm/yyyy hh:ii:ss. - * @param string $date - * @param int - */ - public static function getYear($date) - { - $parts = explode('/', $date); - $year = explode(' ', $parts[2]); - - if (is_array($year)) { - $year = $year[0]; + /** + * Retorna o ano de uma string nos formatos dd/mm/yyyy e dd/mm/yyyy hh:ii:ss. + * + * @param string $date + * + * @return int + */ + public static function getYear($date) + { + $parts = explode('/', $date); + $year = explode(' ', $parts[2]); + + if (is_array($year)) { + $year = $year[0]; + } + + return (int) $year; } - return (int) $year; - } - - /** - * Verifica se ao menos uma das datas de um array é do ano especificado. - * @param array $dates Datas nos formatos dd/mm/yyyy [hh:ii:ss]. - * @param int $year Ano esperado. - * @param int $at Quantidade mínima de datas esperadas no ano $year. - * @return bool TRUE se ao menos uma das datas estiver no ano esperado. - * @throws App_Date_Exception - */ - public static function datesYearAtLeast(array $dates, $year, $at = 1) - { - $matches = 0; - - foreach ($dates as $date) { - $dateYear = self::getYear($date); - if ($year == $dateYear) { - $matches++; - } + /** + * Verifica se ao menos uma das datas de um array é do ano especificado. + * + * @param array $dates Datas nos formatos dd/mm/yyyy [hh:ii:ss]. + * @param int $year Ano esperado. + * @param int $at Quantidade mínima de datas esperadas no ano $year. + * + * @return bool TRUE se ao menos uma das datas estiver no ano esperado. + * + * @throws App_Date_Exception + */ + public static function datesYearAtLeast(array $dates, $year, $at = 1) + { + $matches = 0; + + foreach ($dates as $date) { + $dateYear = self::getYear($date); + + if ($year == $dateYear) { + $matches++; + } + } + + if ($matches >= $at) { + return true; + } + + throw new App_Date_Exception(sprintf( + 'Ao menos "%d" das datas informadas deve ser do ano "%d". Datas: "%s".', + $at, + $year, + implode('", "', $dates) + )); } - - if ($matches >= $at) { - return TRUE; - } - - throw new App_Date_Exception(sprintf( - 'Ao menos "%d" das datas informadas deve ser do ano "%d". Datas: "%s".', - $at, $year, implode('", "', $dates) - )); - } -} \ No newline at end of file +} diff --git a/ieducar/lib/App/Model/ColunaMovimentoGeral.php b/ieducar/lib/App/Model/ColunaMovimentoGeral.php index f9378dd5f0..f7993961bc 100644 --- a/ieducar/lib/App/Model/ColunaMovimentoGeral.php +++ b/ieducar/lib/App/Model/ColunaMovimentoGeral.php @@ -15,7 +15,7 @@ class ColunaMovimentoGeral extends CoreExt_Enum const OITAVO_ANO = 8; const NONO_ANO = 9; - protected $_data = array( + protected $_data = [ self::EDUCACAO_INFANTIL => 'Educação infantil', self::PRIMEIRO_ANO => '1° ano', self::SEGUNDO_ANO => '2° ano', @@ -26,7 +26,7 @@ class ColunaMovimentoGeral extends CoreExt_Enum self::SETIMO_ANO => '7° ano', self::OITAVO_ANO => '8° ano', self::NONO_ANO => '9° ano' - ); + ]; public static function getInstance() { diff --git a/ieducar/lib/App/Model/Educacenso.php b/ieducar/lib/App/Model/Educacenso.php index 0feb044dfc..e03b399f4c 100644 --- a/ieducar/lib/App/Model/Educacenso.php +++ b/ieducar/lib/App/Model/Educacenso.php @@ -4,39 +4,46 @@ class App_Model_Educacenso { public static function etapas_multisseriadas() { - return array(12,13,22,23,24,72,56,64); + return [12, 13, 22, 23, 24, 72, 56, 64]; } public static function etapasEnsinoUnificadas() { - return array(3); + return [3]; } public static function etapasDaTurma($etapaEnsino) { - $etapas = array(); + $etapas = []; + switch ($etapaEnsino) { case '12': case '13': - $etapas = array(4, 5, 6, 7, 8, 9, 10, 11); + $etapas = [4, 5, 6, 7, 8, 9, 10, 11]; break; + case '22': case '23': - $etapas = array(14, 15, 16, 17, 18, 19, 20, 21, 41); + $etapas = [14, 15, 16, 17, 18, 19, 20, 21, 41]; break; + case '24': - $etapas = array(4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 41); + $etapas = [4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 41]; break; + case '72': - $etapas = array(69,70); + $etapas = [69, 70]; break; + case '56': - $etapas = array(1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 41); + $etapas = [1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 41]; break; + case '64': - $etapas = array(39, 40); + $etapas = [39, 40]; break; } + return $etapas; } } diff --git a/ieducar/lib/App/Model/Educacenso/TipoMediacaoDidaticoPedagogico.php b/ieducar/lib/App/Model/Educacenso/TipoMediacaoDidaticoPedagogico.php index a419be5259..ac21ac57c9 100644 --- a/ieducar/lib/App/Model/Educacenso/TipoMediacaoDidaticoPedagogico.php +++ b/ieducar/lib/App/Model/Educacenso/TipoMediacaoDidaticoPedagogico.php @@ -4,18 +4,18 @@ class App_Model_TipoMediacaoDidaticoPedagogico extends CoreExt_Enum { - const PRESENCIAL = 1; - const SEMIPRESENCIAL = 2; - const EDUCACAO_A_DISTANCIA = 3; + const PRESENCIAL = 1; + const SEMIPRESENCIAL = 2; + const EDUCACAO_A_DISTANCIA = 3; - protected $_data = array( - self::PRESENCIAL => 'Presencial', - self::SEMIPRESENCIAL => 'Semipresencial', - self::EDUCACAO_A_DISTANCIA => 'Educação a distância', - ); + protected $_data = [ + self::PRESENCIAL => 'Presencial', + self::SEMIPRESENCIAL => 'Semipresencial', + self::EDUCACAO_A_DISTANCIA => 'Educação a distância', + ]; - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } -} \ No newline at end of file + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } +} diff --git a/ieducar/lib/App/Model/Exception.php b/ieducar/lib/App/Model/Exception.php index b55fd79e5f..8f2dc19838 100644 --- a/ieducar/lib/App/Model/Exception.php +++ b/ieducar/lib/App/Model/Exception.php @@ -4,4 +4,4 @@ class App_Model_Exception extends CoreExt_Exception { -} \ No newline at end of file +} diff --git a/ieducar/lib/App/Model/IedFinder.php b/ieducar/lib/App/Model/IedFinder.php index 51aa70c947..e744a2ed7d 100644 --- a/ieducar/lib/App/Model/IedFinder.php +++ b/ieducar/lib/App/Model/IedFinder.php @@ -1,1201 +1,1534 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Entity.php'; require_once 'App/Model/Exception.php'; -// require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; - -/** - * App_Model_IedFinder class. - * - * Disponibiliza finders estáticos para registros mantidos pelas classes - * cls* do namespace Ied_*. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ + class App_Model_IedFinder extends CoreExt_Entity { - /** - * Retorna todas as instituições cadastradas em pmieducar.instituicao. - * @return array - */ - public static function getInstituicoes() - { - $instituicao = self::addClassToStorage('clsPmieducarInstituicao', NULL, - 'include/pmieducar/clsPmieducarInstituicao.inc.php'); - - $instituicoes = array(); - foreach ($instituicao->lista() as $instituicao) { - $instituicoes[$instituicao['cod_instituicao']] = mb_strtoupper($instituicao['nm_instituicao'], 'UTF-8'); - } - return $instituicoes; - } - - /** - * Retorna um array com as informações de escola a partir de seu código. - * @param int $id - * @return array - */ - public static function getEscola($id) - { - $escola = self::addClassToStorage('clsPmieducarEscola', NULL, - 'include/pmieducar/clsPmieducarEscola.inc.php'); - $escola->cod_escola = $id; - $escola = $escola->detalhe(); - - if (FALSE === $escola) { - throw new App_Model_Exception( - sprintf('Escola com o código "%d" não existe.', $id) - ); - } + /** + * Retorna todas as instituições cadastradas em pmieducar.instituicao. + * + * @return array + */ + public static function getInstituicoes() + { + $instituicao = self::addClassToStorage( + 'clsPmieducarInstituicao', + null, + 'include/pmieducar/clsPmieducarInstituicao.inc.php' + ); + + $instituicoes = []; + foreach ($instituicao->lista() as $instituicao) { + $instituicoes[$instituicao['cod_instituicao']] = mb_strtoupper($instituicao['nm_instituicao'], 'UTF-8'); + } - return $escola; - } - - /** - * Retorna todas as escolas cadastradas na tabela pmieducar.escola, selecionando - * opcionalmente pelo código da instituição. - * @param int $instituicaoId - * @return array - */ - public static function getEscolas($instituicaoId = NULL) - { - $_escolas = self::addClassToStorage('clsPmieducarEscola', NULL, - 'include/pmieducar/clsPmieducarEscola.inc.php'); - - $_escolas->setOrderby('nome'); - - $escolas = array(); - foreach ($_escolas->lista(NULL, NULL, NULL, $instituicaoId) as $escola) { - $escolas[$escola['cod_escola']] = $escola['nome']; + return $instituicoes; } - return $escolas; - } - - /** - * Retorna um nome de curso, procurando pelo seu código. - * @param int $id - * @return string|FALSE - */ - public static function getCurso($id) - { - $curso = self::addClassToStorage('clsPmieducarCurso', NULL, - 'include/pmieducar/clsPmieducarCurso.inc.php'); - $curso->cod_curso = $id; - $curso = $curso->detalhe(); - return $curso['nm_curso']; - } - - /** - * Retorna todos os cursos cadastradas na tabela pmieducar.escola_curso, selecionando - * opcionalmente pelo código da escola. - * @param int $escolaId - * @return array - */ - public static function getCursos($escolaId = NULL) - { - $escola_curso = self::addClassToStorage('clsPmieducarEscolaCurso', NULL, - 'include/pmieducar/clsPmieducarEscolaCurso.inc.php'); - - // Carrega os cursos - $escola_curso->setOrderby('ref_cod_escola ASC, cod_curso ASC'); - $escola_curso = $escola_curso->lista($escolaId); - - $cursos = array(); - foreach ($escola_curso as $key => $val) { - $nomeCurso = self::getCurso($val['ref_cod_curso']); - $cursos[$val['ref_cod_curso']] = $nomeCurso; + /** + * Retorna um array com as informações de escola a partir de seu código. + * + * @param int $id + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getEscola($id) + { + $escola = self::addClassToStorage( + 'clsPmieducarEscola', + null, + 'include/pmieducar/clsPmieducarEscola.inc.php' + ); + + $escola->cod_escola = $id; + $escola = $escola->detalhe(); + + if (false === $escola) { + throw new App_Model_Exception( + sprintf('Escola com o código "%d" não existe.', $id) + ); + } + + return $escola; } - return $cursos; - } - - /** - * Retorna um array com as informações da instituição a partir de seu código. - * - * @param int $codInstituicao - * @return array - * @throws App_Model_Exception - */ - public static function getInstituicao($codInstituicao) - { - // Recupera clsPmieducarInstituicao do storage de classe estático - $instituicao = self::addClassToStorage('clsPmieducarInstituicao', NULL, - 'include/pmieducar/clsPmieducarInstituicao.inc.php'); - - // Usa o atributo público para depois chamar o método detalhe() - $instituicao->cod_instituicao = $codInstituicao; - $instituicao = $instituicao->detalhe(); - - if (FALSE === $instituicao) { - throw new App_Model_Exception( - sprintf('Série com o código "%d" não existe.', $codInstituicao) - ); + /** + * Retorna todas as escolas cadastradas na tabela pmieducar.escola, selecionando + * opcionalmente pelo código da instituição. + * + * @param int $instituicaoId + * + * @return array + */ + public static function getEscolas($instituicaoId = null) + { + $_escolas = self::addClassToStorage( + 'clsPmieducarEscola', + null, + 'include/pmieducar/clsPmieducarEscola.inc.php' + ); + + $_escolas->setOrderby('nome'); + + $escolas = []; + + foreach ($_escolas->lista(null, null, null, $instituicaoId) as $escola) { + $escolas[$escola['cod_escola']] = $escola['nome']; + } + + return $escolas; } - return $instituicao; - } - - /** - * Retorna um array com as informações da série a partir de seu código. - * - * @param int $codSerie - * @return array - * @throws App_Model_Exception - */ - public static function getSerie($codSerie) - { - // Recupera clsPmieducarSerie do storage de classe estático - $serie = self::addClassToStorage('clsPmieducarSerie', NULL, - 'include/pmieducar/clsPmieducarSerie.inc.php'); - - // Usa o atributo público para depois chamar o método detalhe() - $serie->cod_serie = $codSerie; - $serie = $serie->detalhe(); - - if (FALSE === $serie) { - throw new App_Model_Exception( - sprintf('Série com o código "%d" não existe.', $codSerie) - ); + /** + * Retorna um nome de curso, procurando pelo seu código. + * + * @param int $id + * + * @return string|FALSE + */ + public static function getCurso($id) + { + $curso = self::addClassToStorage( + 'clsPmieducarCurso', + null, + 'include/pmieducar/clsPmieducarCurso.inc.php' + ); + + $curso->cod_curso = $id; + $curso = $curso->detalhe(); + + return $curso['nm_curso']; } - return $serie; - } - - /** - * Retorna todas as séries cadastradas na tabela pmieducar.serie, selecionando - * opcionalmente pelo código da instituição, da escola ou do curso. - * @param int $instituicaoId - * @param int $escolaId - * @param int $cursoId - * @return array - */ - public static function getSeries($instituicaoId = NULL, $escolaId = NULL, $cursoId = NULL, $ano = NULL) - { - $series = self::addClassToStorage('clsPmieducarSerie', NULL, - 'include/pmieducar/clsPmieducarSerie.inc.php'); - - $series->setOrderby(' nm_serie ASC, ref_cod_curso ASC, cod_serie ASC, etapa_curso ASC'); - $series = $series->lista(NULL, NULL, NULL, $cursoId, NULL, NULL, NULL, NULL, NULL, - NULL, NULL, NULL, NULL, $instituicaoId, NULL, NULL, $escolaId, - NULL, NULL, $ano); - - $_series = array(); - - foreach ($series as $serie) { - //$series[$val['cod_serie']] = $val; - $_series[$serie['cod_serie']] = mb_strtoupper($serie['nm_serie'], 'UTF-8'); + /** + * Retorna todos os cursos cadastradas na tabela pmieducar.escola_curso, selecionando + * opcionalmente pelo código da escola. + * + * @param int $escolaId + * + * @return array + */ + public static function getCursos($escolaId = null) + { + $escola_curso = self::addClassToStorage( + 'clsPmieducarEscolaCurso', + null, + 'include/pmieducar/clsPmieducarEscolaCurso.inc.php' + ); + + // Carrega os cursos + $escola_curso->setOrderby('ref_cod_escola ASC, cod_curso ASC'); + $escola_curso = $escola_curso->lista($escolaId); + + $cursos = []; + + foreach ($escola_curso as $key => $val) { + $nomeCurso = self::getCurso($val['ref_cod_curso']); + $cursos[$val['ref_cod_curso']] = $nomeCurso; + } + + return $cursos; } - return $_series; - } - - /** - * Retorna um array com as informações da turma a partir de seu código. - * - * @param int $codTurma - * @return array - * @throws App_Model_Exception - */ - public static function getTurma($codTurma) - { - // Recupera clsPmieducarTurma do storage de classe estático - $turma = self::addClassToStorage('clsPmieducarTurma', NULL, - 'include/pmieducar/clsPmieducarTurma.inc.php'); - - // Usa o atributo público para depois chamar o método detalhe() - $turma->cod_turma = $codTurma; - $turma = $turma->detalhe(); - - if (FALSE === $turma) { - throw new App_Model_Exception( - sprintf('Turma com o código "%d" não existe.', $codTurma) - ); + /** + * Retorna um array com as informações da instituição a partir de seu código. + * + * @param int $codInstituicao + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getInstituicao($codInstituicao) + { + // Recupera clsPmieducarInstituicao do storage de classe estático + $instituicao = self::addClassToStorage( + 'clsPmieducarInstituicao', + null, + 'include/pmieducar/clsPmieducarInstituicao.inc.php' + ); + + // Usa o atributo público para depois chamar o método detalhe() + $instituicao->cod_instituicao = $codInstituicao; + $instituicao = $instituicao->detalhe(); + + if (false === $instituicao) { + throw new App_Model_Exception( + sprintf('Série com o código "%d" não existe.', $codInstituicao) + ); + } + + return $instituicao; } - return $turma; - } - - /** - * Retorna as turmas de uma escola, selecionando opcionalmente pelo código da série. - * @param int $escolaId - * @param int $serieId - * @return array (cod_turma => nm_turma) - */ - public static function getTurmas($escolaId, $serieId = NULL, $ano = NULL, $ativo = NULL) - { - $turma = self::addClassToStorage('clsPmieducarTurma', NULL, - 'include/pmieducar/clsPmieducarTurma.inc.php'); - - // Carrega as turmas da escola - $turma->setOrderBy('nm_turma ASC'); - $turmas = $turma->lista(NULL, NULL, NULL, $serieId, $escolaId, NULL, NULL, NULL, NULL, NULL,NULL, NULL, - NULL,NULL, $ativo, NULL,NULL, NULL, NULL,NULL, NULL, NULL, NULL, NULL, NULL,NULL, - NULL, NULL,NULL, NULL, NULL,NULL, NULL, NULL,NULL, NULL, $ano); - - $ret = array(); - foreach ($turmas as $turma) { - $ret[$turma['cod_turma']] = $turma['nm_turma'].' - '.($turma['ano'] == null ? 'Sem ano' : $turma['ano'] ); + /** + * Retorna um array com as informações da série a partir de seu código. + * + * @param int $codSerie + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getSerie($codSerie) + { + // Recupera clsPmieducarSerie do storage de classe estático + $serie = self::addClassToStorage( + 'clsPmieducarSerie', + null, + 'include/pmieducar/clsPmieducarSerie.inc.php' + ); + + // Usa o atributo público para depois chamar o método detalhe() + $serie->cod_serie = $codSerie; + $serie = $serie->detalhe(); + + if (false === $serie) { + throw new App_Model_Exception( + sprintf('Série com o código "%d" não existe.', $codSerie) + ); + } + + return $serie; } - return $ret; - } - - /** - * Retorna as turmas de uma escola e ano para exportação do educacenso. - * @param int $escolaId - * @param int $ano - * @return array (cod_turma => nm_turma) - */ - public static function getTurmasEducacenso($escolaId, $ano = NULL) - { - $turma = self::addClassToStorage('clsPmieducarTurma', NULL, - 'include/pmieducar/clsPmieducarTurma.inc.php'); - - // Carrega as turmas da escola - $turma->setOrderBy('nm_turma ASC'); - $turma->listarNaoInformarEducacenso = FALSE; - $turmas = $turma->lista(NULL, NULL, NULL, NULL, $escolaId, NULL, NULL, NULL, NULL, NULL,NULL, NULL, - NULL,NULL, NULL, NULL,NULL, NULL, NULL,NULL, NULL, NULL, NULL, NULL, NULL,NULL, - NULL, NULL,NULL, NULL, NULL,NULL, NULL, NULL,NULL, NULL, $ano); - - $ret = array(); - foreach ($turmas as $turma) { - $ret[$turma['cod_turma']] = $turma['nm_turma'].' - '.($turma['ano'] == null ? 'Sem ano' : $turma['ano'] ); + /** + * Retorna todas as séries cadastradas na tabela pmieducar.serie, selecionando + * opcionalmente pelo código da instituição, da escola ou do curso. + * + * @param int|null $instituicaoId + * @param int|null $escolaId + * @param int|null $cursoId + * @param int|null $ano + * + * @return array + */ + public static function getSeries($instituicaoId = null, $escolaId = null, $cursoId = null, $ano = null) + { + $series = self::addClassToStorage( + 'clsPmieducarSerie', + null, + 'include/pmieducar/clsPmieducarSerie.inc.php' + ); + + $series->setOrderby(' nm_serie ASC, ref_cod_curso ASC, cod_serie ASC, etapa_curso ASC'); + + $series = $series->lista( + null, + null, + null, + $cursoId, + null, + null, + null, + null, + null, + null, + null, + null, + null, + $instituicaoId, + null, + null, + $escolaId, + null, + null, + $ano + ); + + $_series = []; + + foreach ($series as $serie) { + $_series[$serie['cod_serie']] = mb_strtoupper($serie['nm_serie'], 'UTF-8'); + } + + return $_series; } - return $ret; - } - /** - * Retorna o total de módulos do ano letivo da escola ou turma (caso o ano - * escolar do curso não seja "padrão"). Retorna um array com o total de - * módulos atribuídos ao ano letivo e o nome do módulo. Ex: - * - * - * 4, - * 'nome' => 'Bimestre' - * ); - * - * - * @param int $codEscola - * @param int $codCurso - * @param int $codTurma - * @param int|NULL $ano Ano letivo da escola ou turma. Opcional. - * @return array - */ - public static function getModulo($codEscola, $codCurso, $codTurma, - $ano = NULL) - { - $modulos = array(); - - $curso = self::addClassToStorage('clsPmieducarCurso', NULL, - 'include/pmieducar/clsPmieducarCurso.inc.php'); - - $curso->cod_curso = $codCurso; - $curso = $curso->detalhe(); - - $padraoAnoEscolar = $curso['padrao_ano_escolar'] == 1 ? TRUE : FALSE; - - // Segue o padrão - if (TRUE == $padraoAnoEscolar) { - $escolaAnoLetivo = self::addClassToStorage('clsPmieducarEscolaAnoLetivo', - NULL, 'include/pmieducar/clsPmieducarEscolaAnoLetivo.inc.php'); - - $anosEmAndamento = $escolaAnoLetivo->lista($codEscola, $ano, NULL, NULL, - 1, NULL, NULL, NULL, NULL, 1); - - $anoLetivoModulo = self::addClassToStorage('clsPmieducarAnoLetivoModulo', - NULL, 'include/pmieducar/clsPmieducarAnoLetivoModulo.inc.php'); - - $modulos = $anoLetivoModulo->lista($ano, $codEscola); + /** + * Retorna um array com as informações da turma a partir de seu código. + * + * @param int $codTurma + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getTurma($codTurma) + { + // Recupera clsPmieducarTurma do storage de classe estático + $turma = self::addClassToStorage( + 'clsPmieducarTurma', + null, + 'include/pmieducar/clsPmieducarTurma.inc.php' + ); + + // Usa o atributo público para depois chamar o método detalhe() + $turma->cod_turma = $codTurma; + $turma = $turma->detalhe(); + + if (false === $turma) { + throw new App_Model_Exception( + sprintf('Turma com o código "%d" não existe.', $codTurma) + ); + } + + return $turma; } - else { - $turmaModulo = self::addClassToStorage('clsPmieducarTurmaModulo', - NULL, 'include/pmieducar/clsPmieducarTurmaModulo.inc.php'); - $modulos = $turmaModulo->lista($codTurma); + /** + * Retorna as turmas de uma escola, selecionando opcionalmente pelo código da série. + * + * @param int|null $escolaId + * @param int|null $serieId + * @param int|null $ano + * @param int|null $ativo + * + * @return array (cod_turma => nm_turma) + */ + public static function getTurmas($escolaId, $serieId = null, $ano = null, $ativo = null) + { + $turma = self::addClassToStorage( + 'clsPmieducarTurma', + null, + 'include/pmieducar/clsPmieducarTurma.inc.php' + ); + + // Carrega as turmas da escola + $turma->setOrderBy('nm_turma ASC'); + $turmas = $turma->lista( + null, + null, + null, + $serieId, + $escolaId, + null, + null, + null, + null, + null, + null, + null, + null, + null, + $ativo, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + $ano + ); + + $ret = []; + + foreach ($turmas as $turma) { + $ret[$turma['cod_turma']] = $turma['nm_turma'] . ' - ' . ($turma['ano'] == null ? 'Sem ano' : $turma['ano']); + } + + return $ret; } - if (FALSE === $modulos) { - return 0; + /** + * Retorna as turmas de uma escola e ano para exportação do educacenso. + * + * @param int $escolaId + * @param int $ano + * + * @return array (cod_turma => nm_turma) + */ + public static function getTurmasEducacenso($escolaId, $ano = null) + { + $turma = self::addClassToStorage( + 'clsPmieducarTurma', + null, + 'include/pmieducar/clsPmieducarTurma.inc.php' + ); + + // Carrega as turmas da escola + $turma->setOrderBy('nm_turma ASC'); + $turma->listarNaoInformarEducacenso = false; + + $turmas = $turma->lista( + null, + null, + null, + null, + $escolaId, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + $ano + ); + + $ret = []; + + foreach ($turmas as $turma) { + $ret[$turma['cod_turma']] = $turma['nm_turma'] . ' - ' . ($turma['ano'] == null ? 'Sem ano' : $turma['ano']); + } + + return $ret; } - // Total de módulos - $total = count($modulos); + /** + * Retorna o total de módulos do ano letivo da escola ou turma (caso o ano + * escolar do curso não seja "padrão"). Retorna um array com o total de + * módulos atribuídos ao ano letivo e o nome do módulo. Ex: + * + * + * 4, + * 'nome' => 'Bimestre' + * ); + * + * + * @param int $codEscola + * @param int $codCurso + * @param int $codTurma + * @param int|NULL $ano Ano letivo da escola ou turma. Opcional. + * + * @return array + */ + public static function getModulo( + $codEscola, + $codCurso, + $codTurma, + $ano = null + ) { + $modulos = []; + + $curso = self::addClassToStorage( + 'clsPmieducarCurso', + null, + 'include/pmieducar/clsPmieducarCurso.inc.php' + ); - // Código do tipo de módulo - $modulo = array_shift($modulos); - $codModulo = $modulo['ref_cod_modulo']; + $curso->cod_curso = $codCurso; + $curso = $curso->detalhe(); + + $padraoAnoEscolar = $curso['padrao_ano_escolar'] == 1 ? true : false; + + // Segue o padrão + if (true == $padraoAnoEscolar) { + $escolaAnoLetivo = self::addClassToStorage( + 'clsPmieducarEscolaAnoLetivo', + null, + 'include/pmieducar/clsPmieducarEscolaAnoLetivo.inc.php' + ); + + $anosEmAndamento = $escolaAnoLetivo->lista( + $codEscola, + $ano, + null, + null, + 1, + null, + null, + null, + null, + 1 + ); + + $anoLetivoModulo = self::addClassToStorage( + 'clsPmieducarAnoLetivoModulo', + null, + 'include/pmieducar/clsPmieducarAnoLetivoModulo.inc.php' + ); + + $modulos = $anoLetivoModulo->lista($ano, $codEscola); + } else { + $turmaModulo = self::addClassToStorage( + 'clsPmieducarTurmaModulo', + null, + 'include/pmieducar/clsPmieducarTurmaModulo.inc.php' + ); + + $modulos = $turmaModulo->lista($codTurma); + } - // Recupera do regstry o objeto legado - $modulo = self::addClassToStorage('clsPmieducarModulo', NULL, - 'include/pmieducar/clsPmieducarModulo.inc.php'); + if (false === $modulos) { + return 0; + } + + // Total de módulos + $total = count($modulos); - $modulo->cod_modulo = $codModulo; - $modulo = $modulo->detalhe(); - $modulo = $modulo['nm_tipo']; + // Código do tipo de módulo + $modulo = array_shift($modulos); + $codModulo = $modulo['ref_cod_modulo']; + + // Recupera do regstry o objeto legado + $modulo = self::addClassToStorage( + 'clsPmieducarModulo', + null, + 'include/pmieducar/clsPmieducarModulo.inc.php' + ); - return array( - 'total' => $total, - 'nome' => $modulo - ); - } + $modulo->cod_modulo = $codModulo; + $modulo = $modulo->detalhe(); + $modulo = $modulo['nm_tipo']; - public static function getAnosLetivosEscolaSerie($escolaId, $serieId) - { - $params = [ $escolaId, $serieId ]; - $sql = "SELECT array_to_json(escola_serie.anos_letivos) as anos_letivos + return [ + 'total' => $total, + 'nome' => $modulo + ]; + } + + public static function getAnosLetivosEscolaSerie($escolaId, $serieId) + { + $params = [$escolaId, $serieId]; + + $sql = ' + SELECT array_to_json(escola_serie.anos_letivos) as anos_letivos FROM pmieducar.escola_serie WHERE escola_serie.ref_cod_escola = $1 AND escola_serie.ref_cod_serie = $2 AND escola_serie.ativo = 1 - LIMIT 1 "; - - $anosLetivos = json_decode(Portabilis_Utils_Database::selectField($sql, $params) ?: '[]'); - return array_combine($anosLetivos, $anosLetivos); - } - - /** - * Retorna array com as referências de pmieducar.escola_serie_disciplina - * a modules.componente_curricular ('ref_ref_cod_disciplina'). - * - * @param int $serieId O código do ano escolar/série. - * @param int $escola O código da escola. - * @param ComponenteCurricular_Model_ComponenteDataMapper $mapper (Opcional) - * Instância do mapper para recuperar todas as instâncias persistidas de - * ComponenteCurricular_Model_Componente atribuídas no ano escolar/série da - * escola. - * @return array - * @throws App_Model_Exception caso não existam componentes curriculares - * atribuídos ao ano escolar/série da escola. - */ - public static function getEscolaSerieDisciplina($serieId, $escolaId, - ComponenteCurricular_Model_ComponenteDataMapper $mapper = NULL, - $disciplinaId = null, $etapa = null, $trazerDetalhes = true, - $ano = null) - { - if (is_null($serieId)) - throw new App_Model_Exception('O parametro serieId não pode ser nulo'); - - if (is_null($escolaId)) - throw new App_Model_Exception('O parametro escolaId não pode ser nulo'); - - // Disciplinas na série na escola - $escolaSerieDisciplina = self::addClassToStorage('clsPmieducarEscolaSerieDisciplina', - NULL, 'include/pmieducar/clsPmieducarEscolaSerieDisciplina.inc.php'); - - $disciplinas = $escolaSerieDisciplina->lista($serieId, $escolaId, $disciplinaId, 1, false, $etapa, $ano); - - if (FALSE === $disciplinas) { - throw new App_Model_Exception(sprintf( - 'Nenhuma disciplina para a série (%d) e a escola (%d) informados', - $serieId, $escolaId - )); + LIMIT 1 + '; + + $anosLetivos = json_decode(Portabilis_Utils_Database::selectField($sql, $params) ?: '[]'); + + return array_combine($anosLetivos, $anosLetivos); } - $componentes = array(); - foreach ($disciplinas as $disciplina) { - $componente = new stdClass(); + /** + * Retorna array com as referências de pmieducar.escola_serie_disciplina + * a modules.componente_curricular ('ref_ref_cod_disciplina'). + * + * @param int $serieId O código do ano escolar/série. + * @param int $escolaId + * @param ComponenteCurricular_Model_ComponenteDataMapper $mapper + * @param null $disciplinaId + * @param null $etapa + * @param bool $trazerDetalhes + * @param null $ano + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getEscolaSerieDisciplina( + $serieId, + $escolaId, + ComponenteCurricular_Model_ComponenteDataMapper $mapper = null, + $disciplinaId = null, + $etapa = null, + $trazerDetalhes = true, + $ano = null + ) { + if (is_null($serieId)) { + throw new App_Model_Exception('O parametro serieId não pode ser nulo'); + } - $componente->id = $disciplina['ref_cod_disciplina']; - $componente->cargaHoraria = $disciplina['carga_horaria']; + if (is_null($escolaId)) { + throw new App_Model_Exception('O parametro escolaId não pode ser nulo'); + } - $componentes[] = $componente; - } - if($trazerDetalhes){ - return self::_hydrateComponentes($componentes, $serieId, $mapper); - }else{ - return $componentes; - } - } - - /** - * Retorna as instâncias de ComponenteCurricular_Model_Componente de uma turma. - * - * @param int $serieId O código do ano escolar/série da turma. - * @param int $escola O código da escola da turma. - * @param int $turma O código da turma. - * @param ComponenteCurricular_Model_TurmaDataMapper $mapper (Opcional) Instância - * do mapper para selecionar todas as referências de - * ComponenteCurricular_Model_Componente persistidas para a turma. - * @param ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper (Opcional) - * Instância do mapper para recuperar as instâncias de - * ComponenteCurricular_Model_Componente recuperadas por $mapper. - * @return array - */ - public static function getComponentesTurma($serieId, $escola, $turma, - ComponenteCurricular_Model_TurmaDataMapper $mapper = NULL, - ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper = NULL, - $componenteCurricularId = null, $etapa = null, $trazerDetalhes = true, - $ano = null) - { - if (is_null($mapper)) { - require_once 'ComponenteCurricular/Model/TurmaDataMapper.php'; - $mapper = new ComponenteCurricular_Model_TurmaDataMapper(); - } + // Disciplinas na série na escola + $escolaSerieDisciplina = self::addClassToStorage( + 'clsPmieducarEscolaSerieDisciplina', + null, + 'include/pmieducar/clsPmieducarEscolaSerieDisciplina.inc.php' + ); + + $disciplinas = $escolaSerieDisciplina->lista($serieId, $escolaId, $disciplinaId, 1, false, $etapa, $ano); + + if (false === $disciplinas) { + throw new App_Model_Exception(sprintf( + 'Nenhuma disciplina para a série (%d) e a escola (%d) informados', + $serieId, + $escolaId + )); + } - $where = array('turma' => $turma); + $componentes = []; - if (is_numeric($componenteCurricularId)) - $where['componente_curricular_id'] = $componenteCurricularId; + foreach ($disciplinas as $disciplina) { + $componente = new stdClass(); - $componentesTurma = $mapper->findAll(array(), $where); + $componente->id = $disciplina['ref_cod_disciplina']; + $componente->cargaHoraria = $disciplina['carga_horaria']; - // Não existem componentes específicos para a turma - if (0 == count($componentesTurma)) { - return self::getEscolaSerieDisciplina($serieId, $escola, $componenteMapper, - $componenteCurricularId, $etapa, $trazerDetalhes, $ano); + $componentes[] = $componente; + } + + if ($trazerDetalhes) { + return self::_hydrateComponentes($componentes, $serieId, $mapper); + } else { + return $componentes; + } } - $componentes = array(); - foreach ($componentesTurma as $componenteTurma) { - $componente = new stdClass(); + /** + * Retorna as instâncias de ComponenteCurricular_Model_Componente de uma turma. + * + * @param int $serieId O código do ano escolar/série da turma. + * @param int $escola O código da escola da turma. + * @param int $turma O código da turma. + * @param ComponenteCurricular_Model_TurmaDataMapper $mapper + * @param ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getComponentesTurma( + $serieId, + $escola, + $turma, + ComponenteCurricular_Model_TurmaDataMapper $mapper = null, + ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper = null, + $componenteCurricularId = null, + $etapa = null, + $trazerDetalhes = true, + $ano = null + ) { + if (is_null($mapper)) { + require_once 'ComponenteCurricular/Model/TurmaDataMapper.php'; + $mapper = new ComponenteCurricular_Model_TurmaDataMapper(); + } + + $where = ['turma' => $turma]; - $componente->id = $componenteTurma->get('componenteCurricular'); - $componente->cargaHoraria = $componenteTurma->cargaHoraria; + if (is_numeric($componenteCurricularId)) { + $where['componente_curricular_id'] = $componenteCurricularId; + } - $disponivelEtapa = true; + $componentesTurma = $mapper->findAll([], $where); + + // Não existem componentes específicos para a turma + if (0 == count($componentesTurma)) { + return self::getEscolaSerieDisciplina( + $serieId, + $escola, + $componenteMapper, + $componenteCurricularId, + $etapa, + $trazerDetalhes, + $ano + ); + } - if ($componenteTurma->etapasEspecificas == 1) { + $componentes = []; + foreach ($componentesTurma as $componenteTurma) { + $componente = new stdClass(); - $etapas = $componenteTurma->etapasUtilizadas; + $componente->id = $componenteTurma->get('componenteCurricular'); + $componente->cargaHoraria = $componenteTurma->cargaHoraria; - $disponivelEtapa = (strpos($etapas, $etapa) === false ? false : true); - } + $disponivelEtapa = true; - if ($disponivelEtapa) { - $componentes[] = $componente; - } - } + if ($componenteTurma->etapasEspecificas == 1) { + $etapas = $componenteTurma->etapasUtilizadas; - if($trazerDetalhes){ - return self::_hydrateComponentes($componentes, $serieId, $componenteMapper); - }else{ - return $componentes; + $disponivelEtapa = (strpos($etapas, $etapa) === false ? false : true); + } + + if ($disponivelEtapa) { + $componentes[] = $componente; + } + } + + if ($trazerDetalhes) { + return self::_hydrateComponentes($componentes, $serieId, $componenteMapper); + } else { + return $componentes; + } } - } - - public static function getTipoNotaComponenteSerie($componenteId, $serieId) - { - $sql = "SELECT tipo_nota - FROM modules.componente_curricular_ano_escolar - WHERE ano_escolar_id = $1 - AND componente_curricular_id = $2"; - - $tipoNota = Portabilis_Utils_Database::fetchPreparedQuery($sql, array('params' => array($serieId, $componenteId), 'return_only' => 'first-row')); - return $tipoNota['tipo_nota']; - } - - /** - * Recupera instâncias persistidas de ComponenteCurricular_Model_Componente, - * retornando-as com a carga horária padrão caso o componente identificado - * em $componentes possua uma carga horária (atributo cargaHoraria) nula. - * - * @param array $componentes (array(stdClass->id, stdClass->cargaHoraria)) - * @param int $anoEscolar O ano escolar/série para recuperar a carga - * horária padrão do componente curricular. - * @param ComponenteCurricular_Model_ComponenteDataMapper $mapper (Opcional) - * O mapper para recuperar a instância persistida com a carga horária padrão. - * @return array - */ - protected static function _hydrateComponentes(array $componentes, $anoEscolar, - ComponenteCurricular_Model_ComponenteDataMapper $mapper = NULL) - { - if (is_null($mapper)) { - require_once 'ComponenteCurricular/Model/ComponenteDataMapper.php'; - $mapper = new ComponenteCurricular_Model_ComponenteDataMapper(); + + public static function getTipoNotaComponenteSerie($componenteId, $serieId) + { + $sql = ' + SELECT tipo_nota + FROM modules.componente_curricular_ano_escolar + WHERE ano_escolar_id = $1 + AND componente_curricular_id = $2 + '; + + $tipoNota = Portabilis_Utils_Database::fetchPreparedQuery($sql, ['params' => [$serieId, $componenteId], 'return_only' => 'first-row']); + + return $tipoNota['tipo_nota']; } - $ret = array(); + /** + * Recupera instâncias persistidas de ComponenteCurricular_Model_Componente, + * retornando-as com a carga horária padrão caso o componente identificado + * em $componentes possua uma carga horária (atributo cargaHoraria) nula. + * + * @param array $componentes + * @param int $anoEscolar + * @param ComponenteCurricular_Model_ComponenteDataMapper $mapper + * + * @return array + * + * @throws Exception + */ + protected static function _hydrateComponentes( + array $componentes, + $anoEscolar, + ComponenteCurricular_Model_ComponenteDataMapper $mapper = null + ) { + if (is_null($mapper)) { + require_once 'ComponenteCurricular/Model/ComponenteDataMapper.php'; + $mapper = new ComponenteCurricular_Model_ComponenteDataMapper(); + } + + $ret = []; - foreach ($componentes as $componentePlaceholder) { - $id = $componentePlaceholder->id; - $carga = $componentePlaceholder->cargaHoraria; + foreach ($componentes as $componentePlaceholder) { + $id = $componentePlaceholder->id; + $carga = $componentePlaceholder->cargaHoraria; - $componente = $mapper->findComponenteCurricularAnoEscolar($id, $anoEscolar); + $componente = $mapper->findComponenteCurricularAnoEscolar($id, $anoEscolar); - if (! is_null($carga)) { - $componente->cargaHoraria = $carga; - } + if (!is_null($carga)) { + $componente->cargaHoraria = $carga; + } - $ret[$id] = $componente; + $ret[$id] = $componente; + } + + return $ret; } - return $ret; - } - - /** - * Retorna um array populado com os dados de uma matricula. - * - * @param int $codMatricula - * @return array - * @throws App_Model_Exception - */ - public static function getMatricula($codMatricula) - { - - $sql = ' SELECT m.cod_matricula, - m.ref_cod_reserva_vaga, - m.ref_ref_cod_escola, - m.ref_ref_cod_serie, - m.ref_usuario_exc, - m.ref_usuario_cad, - m.ref_cod_aluno, - m.aprovado, - m.data_cadastro, - m.data_exclusao, - m.ativo, - m.ano, - m.ultima_matricula, - m.modulo, - formando, - descricao_reclassificacao, - matricula_reclassificacao, - m.ref_cod_curso, - m.matricula_transferencia, - m.semestre, - m.data_matricula, - m.data_cancel, - m.ref_cod_abandono_tipo, - m.turno_pre_matricula, - m.dependencia, - data_saida_escola, - turno_id, - p.nome, - (p.nome) AS nome_upper, - e.ref_cod_instituicao, - mt.ref_cod_turma, - t.nm_turma, - c.carga_horaria AS curso_carga_horaria, - c.hora_falta AS curso_hora_falta, - s.carga_horaria AS serie_carga_horaria, - s.dias_letivos AS serie_dias_letivos, - c.nm_curso AS curso_nome, - s.nm_serie AS serie_nome, - s.concluinte AS serie_concluinte, - rasa.regra_avaliacao_diferenciada_id as serie_regra_avaliacao_diferenciada_id, - rasa.regra_avaliacao_id as serie_regra_avaliacao_id, - e.utiliza_regra_diferenciada as escola_utiliza_regra_diferenciada, - mt.data_enturmacao + /** + * Retorna um array populado com os dados de uma matricula. + * + * @param int $codMatricula + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getMatricula($codMatricula) + { + $sql = ' + SELECT + m.cod_matricula, + m.ref_cod_reserva_vaga, + m.ref_ref_cod_escola, + m.ref_ref_cod_serie, + m.ref_usuario_exc, + m.ref_usuario_cad, + m.ref_cod_aluno, + m.aprovado, + m.data_cadastro, + m.data_exclusao, + m.ativo, + m.ano, + m.ultima_matricula, + m.modulo, + formando, + descricao_reclassificacao, + matricula_reclassificacao, + m.ref_cod_curso, + m.matricula_transferencia, + m.semestre, + m.data_matricula, + m.data_cancel, + m.ref_cod_abandono_tipo, + m.turno_pre_matricula, + m.dependencia, + data_saida_escola, + turno_id, + p.nome, + (p.nome) AS nome_upper, + e.ref_cod_instituicao, + mt.ref_cod_turma, + t.nm_turma, + c.carga_horaria AS curso_carga_horaria, + c.hora_falta AS curso_hora_falta, + s.carga_horaria AS serie_carga_horaria, + s.dias_letivos AS serie_dias_letivos, + c.nm_curso AS curso_nome, + s.nm_serie AS serie_nome, + s.concluinte AS serie_concluinte, + rasa.regra_avaliacao_diferenciada_id as serie_regra_avaliacao_diferenciada_id, + rasa.regra_avaliacao_id as serie_regra_avaliacao_id, + e.utiliza_regra_diferenciada as escola_utiliza_regra_diferenciada, + mt.data_enturmacao FROM pmieducar.matricula m - JOIN pmieducar.aluno a ON a.cod_aluno = m.ref_cod_aluno - JOIN cadastro.pessoa p ON p.idpes = a.ref_idpes - JOIN pmieducar.escola e ON m.ref_ref_cod_escola = e.cod_escola - JOIN pmieducar.matricula_turma mt ON mt.ref_cod_matricula = m.cod_matricula - JOIN pmieducar.turma t ON t.cod_turma = mt.ref_cod_turma - JOIN pmieducar.curso c ON m.ref_cod_curso = c.cod_curso - JOIN pmieducar.serie s ON m.ref_ref_cod_serie = s.cod_serie + JOIN pmieducar.aluno a + ON a.cod_aluno = m.ref_cod_aluno + JOIN cadastro.pessoa p + ON p.idpes = a.ref_idpes + JOIN pmieducar.escola e + ON m.ref_ref_cod_escola = e.cod_escola + JOIN pmieducar.matricula_turma mt + ON mt.ref_cod_matricula = m.cod_matricula + JOIN pmieducar.turma t + ON t.cod_turma = mt.ref_cod_turma + JOIN pmieducar.curso c + ON m.ref_cod_curso = c.cod_curso + JOIN pmieducar.serie s + ON m.ref_ref_cod_serie = s.cod_serie LEFT JOIN modules.regra_avaliacao_serie_ano rasa ON rasa.ano_letivo = m.ano AND rasa.serie_id = s.cod_serie WHERE m.cod_matricula = $1 - AND a.ativo = 1 - AND t.ativo = 1 - AND (mt.ativo = 1 - OR (mt.transferido - OR mt.remanejado - OR mt.reclassificado - OR mt.abandono - OR mt.falecido) - AND (NOT EXISTS - (SELECT 1 - FROM pmieducar.matricula_turma - WHERE matricula_turma.ativo = 1 - AND matricula_turma.ref_cod_matricula = mt.ref_cod_matricula - AND matricula_turma.ref_cod_turma = mt.ref_cod_turma))) + AND a.ativo = 1 + AND t.ativo = 1 + AND + ( + mt.ativo = 1 + OR + ( + mt.transferido + OR mt.remanejado + OR mt.reclassificado + OR mt.abandono + OR mt.falecido + ) + AND + ( + NOT EXISTS + ( + SELECT 1 + FROM pmieducar.matricula_turma + WHERE matricula_turma.ativo = 1 + AND matricula_turma.ref_cod_matricula = mt.ref_cod_matricula + AND matricula_turma.ref_cod_turma = mt.ref_cod_turma + ) + ) + ) LIMIT 1 - '; - $matricula = Portabilis_Utils_Database::selectRow($sql,array('params' => $codMatricula));; + $matricula = Portabilis_Utils_Database::selectRow($sql, ['params' => $codMatricula]); + ; - if (!$matricula) { - throw new App_Model_Exception('Aluno não enturmado.'); - } elseif(empty($matricula['serie_regra_avaliacao_id'])) { - throw new App_Model_Exception('Regra de avaliação não informada na série para o ano letivo informado.'); - } + if (!$matricula) { + throw new App_Model_Exception('Aluno não enturmado.'); + } elseif (empty($matricula['serie_regra_avaliacao_id'])) { + throw new App_Model_Exception('Regra de avaliação não informada na série para o ano letivo informado.'); + } - return $matricula; - } - - /** - * Retorna uma instância de RegraAvaliacao_Model_Regra a partir dos dados - * da matrícula. - * - * @param int $codMatricula - * @param RegraAvaliacao_Model_RegraDataMapper $mapper - * @param array $matricula - * @return RegraAvaliacao_Model_Regra - * @throws App_Model_Exception - */ - public static function getRegraAvaliacaoPorMatricula($codMatricula, - RegraAvaliacao_Model_RegraDataMapper $mapper = NULL, $matricula = null) - { - if(empty($matricula)){ - $matricula = self::getMatricula($codMatricula); + return $matricula; } - $possuiDeficiencia = self::verificaSePossuiDeficiencia($matricula['ref_cod_aluno']); - if (is_null($mapper)) { - require_once 'RegraAvaliacao/Model/RegraDataMapper.php'; - $mapper = new RegraAvaliacao_Model_RegraDataMapper(); - } + /** + * Retorna uma instância de RegraAvaliacao_Model_Regra a partir dos dados + * da matrícula. + * + * @param int $codMatricula + * @param RegraAvaliacao_Model_RegraDataMapper $mapper + * @param array $matricula + * + * @return RegraAvaliacao_Model_Regra + * + * @throws App_Model_Exception + */ + public static function getRegraAvaliacaoPorMatricula( + $codMatricula, + RegraAvaliacao_Model_RegraDataMapper $mapper = null, + $matricula = null + ) { + if (empty($matricula)) { + $matricula = self::getMatricula($codMatricula); + } - if(dbBool($matricula['escola_utiliza_regra_diferenciada']) && is_numeric($matricula['serie_regra_avaliacao_diferenciada_id']) ) - $intRegra = $matricula['serie_regra_avaliacao_diferenciada_id']; - else - $intRegra = $matricula['serie_regra_avaliacao_id']; + $possuiDeficiencia = self::verificaSePossuiDeficiencia($matricula['ref_cod_aluno']); - $regra = $mapper->find($intRegra); - if($possuiDeficiencia && $regra->regraDiferenciada){ - $regra = $regra->regraDiferenciada; - } + if (is_null($mapper)) { + require_once 'RegraAvaliacao/Model/RegraDataMapper.php'; + $mapper = new RegraAvaliacao_Model_RegraDataMapper(); + } - return $regra; - } - - /** - * Retorna uma instância de RegraAvaliacao_Model_Regra a partir dos dados - * da turma. - * - * @param int $turmaId - * @param RegraAvaliacao_Model_RegraDataMapper $mapper - * @return RegraAvaliacao_Model_Regra - * @throws App_Model_Exception - */ - public static function getRegraAvaliacaoPorTurma($turmaId, - RegraAvaliacao_Model_RegraDataMapper $mapper = NULL) - { - $turma = self::getTurma($turmaId); - $serie = self::getSerie($turma['ref_ref_cod_serie']); - $escola = self::getEscola($turma['ref_ref_cod_escola']); - - if (is_null($mapper)) { - require_once 'RegraAvaliacao/Model/RegraDataMapper.php'; - $mapper = new RegraAvaliacao_Model_RegraDataMapper(); + if (dbBool($matricula['escola_utiliza_regra_diferenciada']) && is_numeric($matricula['serie_regra_avaliacao_diferenciada_id'])) { + $intRegra = $matricula['serie_regra_avaliacao_diferenciada_id']; + } else { + $intRegra = $matricula['serie_regra_avaliacao_id']; + } + + $regra = $mapper->find($intRegra); + + if ($possuiDeficiencia && $regra->regraDiferenciada) { + $regra = $regra->regraDiferenciada; + } + + return $regra; } - if(dbBool($escola['utiliza_regra_diferenciada']) && is_numeric($serie['regra_avaliacao_diferenciada_id']) ) - $intRegra = $serie['regra_avaliacao_diferenciada_id']; - else - $intRegra = $serie['regra_avaliacao_id']; - - return $mapper->find($intRegra); - } - - /** - * Retorna um array de instâncias ComponenteCurricular_Model_Componente ao - * qual um aluno cursa através de sua matrícula. - * - * Exclui todas os componentes curriculares ao qual o aluno está dispensado - * de cursar. - * - * @param int $codMatricula - * @param ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper - * @param ComponenteCurricular_Model_TurmaDataMapper $turmaMapper - * @return array - * @throws App_Model_Exception - */ - public static function getComponentesPorMatricula($codMatricula, - ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper = NULL, - ComponenteCurricular_Model_TurmaDataMapper $turmaMapper = NULL, - $componenteCurricularId = null, $etapa = null, $turma = null, - $matricula = null, $trazerDetalhes = true -) - { - if(empty($matricula)){ - $matricula = self::getMatricula($codMatricula); + /** + * Retorna uma instância de RegraAvaliacao_Model_Regra a partir dos dados + * da turma. + * + * @param int $turmaId + * @param RegraAvaliacao_Model_RegraDataMapper $mapper + * + * @return RegraAvaliacao_Model_Regra + * + * @throws App_Model_Exception + */ + public static function getRegraAvaliacaoPorTurma( + $turmaId, + RegraAvaliacao_Model_RegraDataMapper $mapper = null + ) { + $turma = self::getTurma($turmaId); + $serie = self::getSerie($turma['ref_ref_cod_serie']); + $escola = self::getEscola($turma['ref_ref_cod_escola']); + + if (is_null($mapper)) { + require_once 'RegraAvaliacao/Model/RegraDataMapper.php'; + $mapper = new RegraAvaliacao_Model_RegraDataMapper(); + } + + if (dbBool($escola['utiliza_regra_diferenciada']) && is_numeric($serie['regra_avaliacao_diferenciada_id'])) { + $intRegra = $serie['regra_avaliacao_diferenciada_id']; + } else { + $intRegra = $serie['regra_avaliacao_id']; + } + + return $mapper->find($intRegra); } - $codEscola = $matricula['ref_ref_cod_escola']; - $codSerie = $matricula['ref_ref_cod_serie']; - $ano = $matricula['ano']; + /** + * Retorna um array de instâncias ComponenteCurricular_Model_Componente ao + * qual um aluno cursa através de sua matrícula. + * + * Exclui todas os componentes curriculares ao qual o aluno está dispensado + * de cursar. + * + * @param int $codMatricula + * @param ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper + * @param ComponenteCurricular_Model_TurmaDataMapper $turmaMapper + * @param int|null $componenteCurricularId + * @param int|null $etapa + * @param int|null $turma + * @param int|null $matricula + * @param bool $trazerDetalhes + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getComponentesPorMatricula( + $codMatricula, + ComponenteCurricular_Model_ComponenteDataMapper $componenteMapper = null, + ComponenteCurricular_Model_TurmaDataMapper $turmaMapper = null, + $componenteCurricularId = null, + $etapa = null, + $turma = null, + $matricula = null, + $trazerDetalhes = true + ) { + if (empty($matricula)) { + $matricula = self::getMatricula($codMatricula); + } - if (!$turma) { - $turma = $matricula['ref_cod_turma']; + $codEscola = $matricula['ref_ref_cod_escola']; + $codSerie = $matricula['ref_ref_cod_serie']; + $ano = $matricula['ano']; + + if (!$turma) { + $turma = $matricula['ref_cod_turma']; + } + + $serie = self::getSerie($codSerie); + + $ret = []; + + if (is_numeric($turma) && is_numeric($codSerie) && is_numeric($codEscola)) { + + // Disciplinas da escola na série em que o aluno está matriculado + $componentes = self::getComponentesTurma( + $codSerie, + $codEscola, + $turma, + $turmaMapper, + $componenteMapper, + $componenteCurricularId, + $etapa, + $trazerDetalhes, + $ano + ); + + // Dispensas do aluno + $disciplinasDispensa = self::getDisciplinasDispensadasPorMatricula( + $codMatricula, + $codSerie, + $codEscola, + $etapa + ); + + if (dbBool($matricula['dependencia'])) { + + // Disciplinas dependência + $disciplinasDependencia = self::getDisciplinasDependenciaPorMatricula( + $codMatricula, + $codSerie, + $codEscola + ); + + foreach ($componentes as $id => $componente) { + if (in_array($id, $disciplinasDispensa)) { + continue; + } + + if (!in_array($id, $disciplinasDependencia)) { + continue; + } + + $ret[$id] = $componente; + } + } else { + foreach ($componentes as $id => $componente) { + if (in_array($id, $disciplinasDispensa)) { + continue; + } + + $ret[$id] = $componente; + } + } + } + + return $ret; } - $serie = self::getSerie($codSerie); + /** + * Retorna array com as referências de pmieducar.dispensa_disciplina + * a modules.componente_curricular ('ref_ref_cod_disciplina'). + * + * @param int $codMatricula + * @param int $codSerie + * @param int $codEscola + * + * @return array + */ + public static function getDisciplinasDispensadasPorMatricula( + $codMatricula, + $codSerie, + $codEscola, + $etapa + ) { + $dispensas = self::addClassToStorage( + 'clsPmieducarDispensaDisciplina', + null, + 'include/pmieducar/clsPmieducarDispensaDisciplina.inc.php' + ); - $ret = array(); + $dispensas = $dispensas->disciplinaDispensadaEtapa($codMatricula, $codSerie, $codEscola, $etapa); - if(is_numeric($turma) && is_numeric($codSerie) && is_numeric($codEscola)){ + if (false === $dispensas) { + return []; + } - // Disciplinas da escola na série em que o aluno está matriculado - $componentes = self::getComponentesTurma( - $codSerie, $codEscola, $turma, $turmaMapper, $componenteMapper, - $componenteCurricularId, $etapa, $trazerDetalhes, $ano - ); + $disciplinasDispensa = []; - // Dispensas do aluno - $disciplinasDispensa = self::getDisciplinasDispensadasPorMatricula( - $codMatricula, $codSerie, $codEscola, $etapa - ); + foreach ($dispensas as $dispensa) { + $disciplinasDispensa[] = $dispensa['ref_cod_disciplina']; + } - if(dbBool($matricula['dependencia'])){ + return $disciplinasDispensa; + } - // Disciplinas dependência - $disciplinasDependencia = self::getDisciplinasDependenciaPorMatricula( - $codMatricula, $codSerie, $codEscola + public static function validaDispensaPorMatricula( + $codMatricula, + $codSerie, + $codEscola, + $disciplina + ) { + $dispensas = self::addClassToStorage( + 'clsPmieducarDispensaDisciplina', + null, + 'include/pmieducar/clsPmieducarDispensaDisciplina.inc.php' ); - foreach ($componentes as $id => $componente) { - if (in_array($id, $disciplinasDispensa)) { - continue; - } - if (!in_array($id, $disciplinasDependencia)) { - continue; - } + $dispensas = $dispensas->disciplinaDispensadaEtapa($codMatricula, $codSerie, $codEscola); - $ret[$id] = $componente; + $etapaDispensada = []; + + foreach ($dispensas as $dispensa) { + if ($dispensa['ref_cod_disciplina'] == $disciplina) { + $etapaDispensada[] = $dispensa['etapa']; + } } + return $etapaDispensada; + } - }else{ - foreach ($componentes as $id => $componente) { - if (in_array($id, $disciplinasDispensa)) { - continue; - } + /** + * Retorna array com as referências de pmieducar.disciplina_dependencia + * a modules.componente_curricular ('ref_ref_cod_disciplina'). + * + * @param int $codMatricula + * @param int $codSerie + * @param int $codEscola + * + * @return array + */ + public static function getDisciplinasDependenciaPorMatricula( + $codMatricula, + $codSerie, + $codEscola + ) { + $disciplinas = self::addClassToStorage( + 'clsPmieducarDisciplinaDependencia', + null, + 'include/pmieducar/clsPmieducarDisciplinaDependencia.inc.php' + ); + + $disciplinas = $disciplinas->lista($codMatricula, $codSerie, $codEscola); - $ret[$id] = $componente; + if (false === $disciplinas) { + return []; } - } - } - return $ret; - } - - /** - * Retorna array com as referências de pmieducar.dispensa_disciplina - * a modules.componente_curricular ('ref_ref_cod_disciplina'). - * - * @param int $codMatricula - * @param int $codSerie - * @param int $codEscola - * @return array - */ - public static function getDisciplinasDispensadasPorMatricula($codMatricula, - $codSerie, $codEscola, $etapa) - { - $dispensas = self::addClassToStorage('clsPmieducarDispensaDisciplina', - NULL, 'include/pmieducar/clsPmieducarDispensaDisciplina.inc.php'); - - $dispensas = $dispensas->disciplinaDispensadaEtapa($codMatricula, $codSerie, $codEscola, $etapa); - - if (FALSE === $dispensas) { - return array(); - } + $disciplinasDependencia = []; + + foreach ($disciplinas as $disciplina) { + $disciplinasDependencia[] = $disciplina['ref_cod_disciplina']; + } - $disciplinasDispensa = array(); - foreach ($dispensas as $dispensa) { - $disciplinasDispensa[] = $dispensa['ref_cod_disciplina']; + return $disciplinasDependencia; } - return $disciplinasDispensa; - } + /** + * Retorna a quantidade de módulos do ano letivo por uma dada matrícula. + * + * @param int $codMatricula + * @param array $matricula + * + * @return int + * + * @throws App_Model_Exception + */ + public static function getQuantidadeDeModulosMatricula($codMatricula, $matricula = null) + { + $modulos = []; - public static function validaDispensaPorMatricula($codMatricula, - $codSerie, $codEscola, $disciplina) - { - $dispensas = self::addClassToStorage('clsPmieducarDispensaDisciplina', - NULL, 'include/pmieducar/clsPmieducarDispensaDisciplina.inc.php'); + // matricula + if (empty($matricula)) { + $matricula = self::getMatricula($codMatricula); + } - $dispensas = $dispensas->disciplinaDispensadaEtapa($codMatricula, $codSerie, $codEscola); + $codEscola = $matricula['ref_ref_cod_escola']; + $codCurso = $matricula['ref_cod_curso']; + $codTurma = $matricula['ref_cod_turma']; + $ano = $matricula['ano']; - $etapaDispensada = array(); + $modulos = self::getModulo($codEscola, $codCurso, $codTurma, $ano); - foreach ($dispensas as $dispensa) { - if ($dispensa['ref_cod_disciplina'] == $disciplina) { - $etapaDispensada[] = $dispensa['etapa']; - } + return $modulos['total']; } - return $etapaDispensada; - } - - /** - * Retorna array com as referências de pmieducar.disciplina_dependencia - * a modules.componente_curricular ('ref_ref_cod_disciplina'). - * - * @param int $codMatricula - * @param int $codSerie - * @param int $codEscola - * @return array - */ - public static function getDisciplinasDependenciaPorMatricula($codMatricula, - $codSerie, $codEscola) - { - - $disciplinas = self::addClassToStorage('clsPmieducarDisciplinaDependencia', - NULL, 'include/pmieducar/clsPmieducarDisciplinaDependencia.inc.php'); - - $disciplinas = $disciplinas->lista($codMatricula, $codSerie, $codEscola); - - if (FALSE === $disciplinas) { - return array(); - } + /** + * Retorna um array com as informações de biblioteca a partir de seu código. + * + * @param int $id + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getBiblioteca($id) + { + $biblioteca = self::addClassToStorage( + 'clsPmieducarBiblioteca', + null, + 'include/pmieducar/clsPmieducarBiblioteca.inc.php' + ); + + $biblioteca->cod_biblioteca = $id; + $biblioteca = $biblioteca->detalhe(); - $disciplinasDependencia = array(); - foreach ($disciplinas as $disciplina) { - $disciplinasDependencia[] = $disciplina['ref_cod_disciplina']; + if (false === $biblioteca) { + throw new App_Model_Exception( + sprintf('Seu usuário não está vinculado a nenhuma biblioteca.', $id) + ); + } + + return $biblioteca; } - return $disciplinasDependencia; - } - - /** - * Retorna a quantidade de módulos do ano letivo por uma dada matrícula. - * - * @param int $codMatricula - * @param array $matricula - * @return int - */ - public static function getQuantidadeDeModulosMatricula($codMatricula, $matricula = null) - { - $modulos = array(); - - // matricula - if(empty($matricula)){ - $matricula = self::getMatricula($codMatricula); + /** + * Retorna todas as bibliotecas cadastradas na tabela pmieducar.biblioteca, selecionando + * opcionalmente pelo código da instituição e/ ou escola. + * + * @param int $instituicaoId + * + * @return array + */ + public static function getBibliotecas($instituicaoId = null, $escolaId = null) + { + $_bibliotecas = self::addClassToStorage( + 'clsPmieducarBiblioteca', + null, + 'include/pmieducar/clsPmieducarBiblioteca.inc.php' + ); + + $bibliotecas = []; + + foreach ($_bibliotecas->lista(null, $instituicaoId, $escolaId) as $biblioteca) { + $bibliotecas[$biblioteca['cod_biblioteca']] = $biblioteca['nm_biblioteca']; + } + + return $bibliotecas; } - $codEscola = $matricula['ref_ref_cod_escola']; - $codCurso = $matricula['ref_cod_curso']; - $codTurma = $matricula['ref_cod_turma']; - $ano = $matricula['ano']; - - $modulos = self::getModulo($codEscola, $codCurso, $codTurma, $ano); - - return $modulos['total']; - } - - /** - * Retorna um array com as informações de biblioteca a partir de seu código. - * @param int $id - * @return array - */ - public static function getBiblioteca($id) - { - $biblioteca = self::addClassToStorage('clsPmieducarBiblioteca', NULL, - 'include/pmieducar/clsPmieducarBiblioteca.inc.php'); - $biblioteca->cod_biblioteca = $id; - $biblioteca = $biblioteca->detalhe(); - - if (FALSE === $biblioteca) { - throw new App_Model_Exception( - sprintf("Seu usuário não está vinculado a nenhuma biblioteca.", $id) - ); + /** + * Retorna todas as situações cadastradas para as bibliotecas na tabela pmieducar.situacao, selecionando + * opcionalmente pelo código da biblioteca. + * + * @param int $bibliotecaId + * + * @return array + */ + public static function getBibliotecaSituacoes($bibliotecaId = null) + { + $_situacoes = self::addClassToStorage( + 'clsPmieducarSituacao', + null, + 'include/pmieducar/clsPmieducarSituacao.inc.php' + ); + + $situacoes = []; + + foreach ($_situacoes->lista(null, null, null, null, null, null, null, null, null, null, null, null, null, $bibliotecaId) as $situacao) { + $situacoes[$situacao['cod_situacao']] = $situacao['nm_situacao']; + } + + return $situacoes; } - return $biblioteca; - } - - /** - * Retorna todas as bibliotecas cadastradas na tabela pmieducar.biblioteca, selecionando - * opcionalmente pelo código da instituição e/ ou escola. - * @param int $instituicaoId - * @return array - */ - public static function getBibliotecas($instituicaoId = NULL, $escolaId = NULL) - { - $_bibliotecas = self::addClassToStorage('clsPmieducarBiblioteca', NULL, - 'include/pmieducar/clsPmieducarBiblioteca.inc.php'); - - $bibliotecas = array(); - foreach ($_bibliotecas->lista(NULL, $instituicaoId, $escolaId) as $biblioteca) { - $bibliotecas[$biblioteca['cod_biblioteca']] = $biblioteca['nm_biblioteca']; + /** + * Retorna todas as fontes cadastradas para as bibliotecas na tabela pmieducar.fonte, selecionando + * opcionalmente pelo código da biblioteca. + * + * @param int $bibliotecaId + * + * @return array + */ + public static function getBibliotecaFontes($bibliotecaId = null) + { + $_fontes = self::addClassToStorage( + 'clsPmieducarFonte', + null, + 'include/pmieducar/clsPmieducarFonte.inc.php' + ); + + $fontes = []; + + foreach ($_fontes->lista(null, null, null, null, null, null, null, null, null, 1, $bibliotecaId) as $fonte) { + $fontes[$fonte['cod_fonte']] = $fonte['nm_fonte']; + } + + return $fontes; } - return $bibliotecas; - } - - /** - * Retorna todas as situações cadastradas para as bibliotecas na tabela pmieducar.situacao, selecionando - * opcionalmente pelo código da biblioteca. - * @param int $bibliotecaId - * @return array - */ - public static function getBibliotecaSituacoes($bibliotecaId = NULL) - { - $_situacoes = self::addClassToStorage('clsPmieducarSituacao', NULL, - 'include/pmieducar/clsPmieducarSituacao.inc.php'); - - $situacoes = array(); - foreach ($_situacoes->lista(null, null, null, null, null, null, null, null, null, null, null, null, null, $bibliotecaId) as $situacao) { - $situacoes[$situacao['cod_situacao']] = $situacao['nm_situacao']; + /** + * Retorna uma obra cadastrada para uma biblioteca na tabela pmieducar.acervo, selecionando + * obrigatóriamente pelo código da biblioteca e opcionalmente pelo código da obra. + * + * @param int $bibliotecaId + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getBibliotecaObra($bibliotecaId, $id = null) + { + $obra = self::addClassToStorage( + 'clsPmieducarAcervo', + null, + 'include/pmieducar/clsPmieducarAcervo.inc.php' + ); + + $obra->ref_cod_biblioteca = $$bibliotecaId; + $obra->cod_acervo = $id; + $obra = $obra->detalhe(); + + if (false === $obra) { + throw new App_Model_Exception( + sprintf('Obra com o código "%d" não existe.', $id) + ); + } + + return $obra; } - return $situacoes; - } - - /** - * Retorna todas as fontes cadastradas para as bibliotecas na tabela pmieducar.fonte, selecionando - * opcionalmente pelo código da biblioteca. - * @param int $bibliotecaId - * @return array - */ - public static function getBibliotecaFontes($bibliotecaId = NULL) - { - $_fontes = self::addClassToStorage('clsPmieducarFonte', NULL, - 'include/pmieducar/clsPmieducarFonte.inc.php'); - - $fontes = array(); - foreach ($_fontes->lista(null,null,null,null,null,null,null,null,null,1, $bibliotecaId) as $fonte) { - $fontes[$fonte['cod_fonte']] = $fonte['nm_fonte']; + /** + * Retorna um aluno cadastrado para uma escola na tabela pmieducar.aluno, selecionando + * obrigatóriamente pelo código da escola e opcionalmente pelo código do aluno. + * + * @param int $id + * + * @return array + * + * @throws App_Model_Exception + */ + public static function getAluno($escolaId, $id) + { + $aluno = self::addClassToStorage( + 'clsPmieducarAluno', + null, + 'include/pmieducar/clsPmieducarAluno.inc.php' + ); + + $aluno = $aluno->lista($id, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, $escolaId); + + if (false === $aluno) { + throw new App_Model_Exception( + sprintf('Aluno com o código "%d" não existe.', $id) + ); + } + + return $aluno[0]; } - return $fontes; - } - - /** - * Retorna uma obra cadastrada para uma biblioteca na tabela pmieducar.acervo, selecionando - * obrigatóriamente pelo código da biblioteca e opcionalmente pelo código da obra. - * @param int $bibliotecaId - * @return array - */ - public static function getBibliotecaObra($bibliotecaId, $id = NULL) - { - $obra = self::addClassToStorage('clsPmieducarAcervo', NULL, - 'include/pmieducar/clsPmieducarAcervo.inc.php'); - - $obra->ref_cod_biblioteca = $$bibliotecaId; - $obra->cod_acervo = $id; - $obra = $obra->detalhe(); - - if (FALSE === $obra) { - throw new App_Model_Exception( - sprintf('Obra com o código "%d" não existe.', $id) - ); + /** + * Retorna todos os tipos de cliente cadastrados para determinada biblioteca na tabela + * pmieducar.cliente_tipo, selecionando obrigatoriamente pelo código da biblioteca. + * + * @param int $bibliotecaId + * + * @return array + */ + public static function getBibliotecaTiposCliente($bibliotecaId) + { + $resources = self::addClassToStorage( + 'clsPmieducarClienteTipo', + null, + 'include/pmieducar/clsPmieducarClienteTipo.inc.php' + ); + + $filtered_resources = []; + + foreach ($resources->lista(null, $bibliotecaId) as $resource) { + $filtered_resources[$resource['cod_cliente_tipo']] = $resource['nm_tipo']; + } + + return $filtered_resources; } - return $obra; - } - - /** - * Retorna um aluno cadastrado para uma escola na tabela pmieducar.aluno, selecionando - * obrigatóriamente pelo código da escola e opcionalmente pelo código do aluno. - * @param int $id - * @return array - */ - public static function getAluno($escolaId, $id) - { - $aluno = self::addClassToStorage('clsPmieducarAluno', NULL, - 'include/pmieducar/clsPmieducarAluno.inc.php'); - #$aluno->cod_aluno = $id; - #$aluno = $aluno->detalhe(); - - $aluno = $aluno->lista($id, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, $escolaId); - - if (FALSE === $aluno) { - throw new App_Model_Exception( - sprintf('Aluno com o código "%d" não existe.', $id) - ); + /** + *Retorna todas as áreas de conhecimento cadastradas para determinada instituição + * + * @param int $instituicaoId + * + * @return array + * + * @throws Exception + */ + public static function getAreasConhecimento($instituicaoId) + { + $resultado = []; + + $sql = ' + SELECT + area_conhecimento.id AS id_teste, + area_conhecimento.nome AS nome + FROM modules.area_conhecimento + WHERE instituicao_id = $1 + ORDER BY (lower(nome)) ASC + '; + + $resultado = Portabilis_Utils_Database::fetchPreparedQuery($sql, ['params' => $instituicaoId]); + + return $resultado; } - return $aluno[0]; - } - - /** - * Retorna todos os tipos de cliente cadastrados para determinada biblioteca na tabela - * pmieducar.cliente_tipo, selecionando obrigatoriamente pelo código da biblioteca. - * @param int $bibliotecaId - * @return array - */ - public static function getBibliotecaTiposCliente($bibliotecaId) - { - $resources = self::addClassToStorage('clsPmieducarClienteTipo', NULL, - 'include/pmieducar/clsPmieducarClienteTipo.inc.php'); - - $filtered_resources = array(); - foreach ($resources->lista(null, $bibliotecaId) as $resource) { - $filtered_resources[$resource['cod_cliente_tipo']] = $resource['nm_tipo']; + /** + * Retorna todos os turnos + * + * @return array + * + * @throws Exception + */ + public static function getTurnos() + { + $sql = ' + SELECT id, nome + FROM pmieducar.turma_turno + WHERE ativo = 1 + ORDER BY (lower(nome)) ASC + '; + + return Portabilis_Array_Utils::setAsIdValue(Portabilis_Utils_Database::fetchPreparedQuery($sql), 'id', 'nome'); } - return $filtered_resources; - } - /** - *Retorna todas as áreas de conhecimento cadastradas para determinada instituição - * @param int $instituicaoId - * @return array - */ - public static function getAreasConhecimento($instituicaoId){ - - $resultado = array(); - - $sql = 'SELECT area_conhecimento.id AS id_teste, - area_conhecimento.nome AS nome - FROM modules.area_conhecimento - WHERE instituicao_id = $1 - ORDER BY (lower(nome)) ASC'; - - $resultado = Portabilis_Utils_Database::fetchPreparedQuery($sql,array('params' => $instituicaoId)); - - return $resultado; - } - - /** - * Retorna todos os turnos - * @return array - */ - public static function getTurnos(){ - - $sql = 'SELECT id, nome - FROM pmieducar.turma_turno - WHERE ativo = 1 - ORDER BY (lower(nome)) ASC'; - - - return Portabilis_Array_Utils::setAsIdValue(Portabilis_Utils_Database::fetchPreparedQuery($sql), 'id', 'nome'); - } - /** - * @see CoreExt_Entity_Validatable#getDefaultValidatorCollection() - */ - public function getDefaultValidatorCollection() - { - return array(); - } - - /** - * Retorna um array com as etapas a partir da escola e ano letivo. - * - * @param int $ano - * @param int $escola - * @return array - * @throws App_Model_Exception - */ - public static function getEtapasEscola($ano, $escola) - { - $etapas = self::addClassToStorage('clsPmieducarAnoLetivoModulo', NULL, - 'include/pmieducar/clsPmieducarAnoLetivoModulo.inc.php'); - - $etapas->ref_ano = $ano; - $etapas->ref_ref_cod_escola = $escola; - - $etapas = $etapas->getEtapas(); - - $ret = array(); - foreach ($etapas as $etapa) { - $ret[$etapa['id']] = $etapa['nome']; + /** + * @see CoreExt_Entity_Validatable#getDefaultValidatorCollection() + */ + public function getDefaultValidatorCollection() + { + return []; } - return $ret; - } + /** + * Retorna um array com as etapas a partir da escola e ano letivo. + * + * @param int $ano + * @param int $escola + * + * @return array + */ + public static function getEtapasEscola($ano, $escola) + { + $etapas = self::addClassToStorage( + 'clsPmieducarAnoLetivoModulo', + null, + 'include/pmieducar/clsPmieducarAnoLetivoModulo.inc.php' + ); - /** - * Retorna um array com as etapas definidas para o componente, - * quando a regra "Permitir definir componentes em etapas específicas" estiver sendo utilizada. - * - * @param int $turma - * @param int $componente - * @return array - * @throws App_Model_Exception - */ - public static function getEtapasComponente($turma, $componente) { + $etapas->ref_ano = $ano; + $etapas->ref_ref_cod_escola = $escola; - $resultado = array(); + $etapas = $etapas->getEtapas(); - $sql = 'SELECT componente_curricular_turma.etapas_utilizadas - FROM modules.componente_curricular_turma - WHERE componente_curricular_turma.turma_id = $1 - AND componente_curricular_turma.componente_curricular_id = $2 - AND componente_curricular_turma.etapas_especificas = 1'; + $ret = []; - $resultado = Portabilis_Utils_Database::fetchPreparedQuery($sql,array('params' => array($turma, $componente))); + foreach ($etapas as $etapa) { + $ret[$etapa['id']] = $etapa['nome']; + } - if ($resultado) { - return $resultado[0]["etapas_utilizadas"]; + return $ret; } - $sql = 'SELECT escola_serie_disciplina.etapas_utilizadas - FROM pmieducar.escola_serie_disciplina - INNER JOIN pmieducar.turma ON (turma.ref_ref_cod_serie = escola_serie_disciplina.ref_ref_cod_serie - AND turma.ref_ref_cod_escola = escola_serie_disciplina.ref_ref_cod_escola) - WHERE turma.cod_turma = $1 - AND escola_serie_disciplina.ref_cod_disciplina = $2 - AND escola_serie_disciplina.etapas_especificas = 1'; + /** + * Retorna um array com as etapas definidas para o componente, + * quando a regra "Permitir definir componentes em etapas específicas" estiver sendo utilizada. + * + * @param int $turma + * @param int $componente + * + * @return array + * + * @throws Exception + */ + public static function getEtapasComponente($turma, $componente) + { + $resultado = []; - $resultado = Portabilis_Utils_Database::fetchPreparedQuery($sql,array('params' => array($turma, $componente))); + $sql = ' + SELECT componente_curricular_turma.etapas_utilizadas + FROM modules.componente_curricular_turma + WHERE componente_curricular_turma.turma_id = $1 + AND componente_curricular_turma.componente_curricular_id = $2 + AND componente_curricular_turma.etapas_especificas = 1 + '; - if ($resultado) { - return $resultado[0]["etapas_utilizadas"]; - } + $resultado = Portabilis_Utils_Database::fetchPreparedQuery($sql, ['params' => [$turma, $componente]]); - return null; - } + if ($resultado) { + return $resultado[0]['etapas_utilizadas']; + } - //Retorna a quantidade de etapas resgatadas na function getEtapasComponente - public static function getQtdeEtapasComponente($turma, $componente) { - $resultado = self::getEtapasComponente($turma, $componente); + $sql = ' + SELECT escola_serie_disciplina.etapas_utilizadas + FROM pmieducar.escola_serie_disciplina + INNER JOIN pmieducar.turma ON (turma.ref_ref_cod_serie = escola_serie_disciplina.ref_ref_cod_serie + AND turma.ref_ref_cod_escola = escola_serie_disciplina.ref_ref_cod_escola) + WHERE turma.cod_turma = $1 + AND escola_serie_disciplina.ref_cod_disciplina = $2 + AND escola_serie_disciplina.etapas_especificas = 1 + '; - if (!$resultado) return null; + $resultado = Portabilis_Utils_Database::fetchPreparedQuery($sql, ['params' => [$turma, $componente]]); - $resultado = explode(",",$resultado); + if ($resultado) { + return $resultado[0]['etapas_utilizadas']; + } - return count($resultado); - } + return null; + } - //Retorna a ultima etapa resgatada na function getEtapasComponente - public static function getUltimaEtapaComponente($turma, $componente) { - $resultado = self::getEtapasComponente($turma, $componente); + //Retorna a quantidade de etapas resgatadas na function getEtapasComponente + public static function getQtdeEtapasComponente($turma, $componente) + { + $resultado = self::getEtapasComponente($turma, $componente); - if (!$resultado) return null; + if (!$resultado) { + return null; + } + + $resultado = explode(',', $resultado); - $resultado = explode(",",$resultado); + return count($resultado); + } - return max($resultado); - } + //Retorna a ultima etapa resgatada na function getEtapasComponente + public static function getUltimaEtapaComponente($turma, $componente) + { + $resultado = self::getEtapasComponente($turma, $componente); - public static function verificaSeExisteNotasComponenteCurricular($matricula, $componente) { + if (!$resultado) { + return null; + } - $cc_nota = "SELECT count(ncc.componente_curricular_id) AS cc - FROM modules.nota_aluno AS na - INNER JOIN modules.nota_componente_curricular AS ncc ON (na.id = ncc.nota_aluno_id) - WHERE na.matricula_id = $1 - AND ncc.componente_curricular_id = $2"; + $resultado = explode(',', $resultado); - $resultado = Portabilis_Utils_Database::fetchPreparedQuery($cc_nota,array('params' => array($matricula, $componente))); + return max($resultado); + } + + public static function verificaSeExisteNotasComponenteCurricular($matricula, $componente) + { + $cc_nota = ' + SELECT count(ncc.componente_curricular_id) AS cc + FROM modules.nota_aluno AS na + INNER JOIN modules.nota_componente_curricular AS ncc ON (na.id = ncc.nota_aluno_id) + WHERE na.matricula_id = $1 + AND ncc.componente_curricular_id = $2 + '; - return $resultado; - } + $resultado = Portabilis_Utils_Database::fetchPreparedQuery($cc_nota, ['params' => [$matricula, $componente]]); - public static function verificaSePossuiDeficiencia($alunoId) { + return $resultado; + } - $sql = 'SELECT 1 + public static function verificaSePossuiDeficiencia($alunoId) + { + $sql = ' + SELECT 1 FROM cadastro.fisica_deficiencia fd JOIN PMIEDUCAR.ALUNO A ON fd.ref_idpes = a.ref_idpes @@ -1203,76 +1536,86 @@ public static function verificaSePossuiDeficiencia($alunoId) { ON d.cod_deficiencia = fd.ref_cod_deficiencia WHERE a.cod_aluno = $1 AND d.desconsidera_regra_diferenciada = false - LIMIT 1 '; - - return Portabilis_Utils_Database::selectField($sql,array('params' => array($alunoId))) == 1; - } - - public static function getNotasLancadasAluno($ref_cod_matricula, $ref_cod_disciplina, $etapa) { - - $notas_lancadas_aluno = "SELECT na.matricula_id, - ncc.componente_curricular_id, - ncc.nota, - ncc.nota_recuperacao, - ncc.nota_recuperacao_especifica, - ncc.etapa - FROM modules.nota_aluno AS na - INNER JOIN modules.nota_componente_curricular AS ncc ON (na.id = ncc.nota_aluno_id) - WHERE na.matricula_id = $1 - AND ncc.componente_curricular_id = $2 - AND ncc.etapa = $3"; - - $resultado = Portabilis_Utils_Database::fetchPreparedQuery($notas_lancadas_aluno,array('params' => array($ref_cod_matricula, $ref_cod_disciplina, $etapa))); - - return $resultado; - } - - public static function getFaltasLancadasAluno($ref_cod_matricula, $ref_cod_disciplina, $etapa) { - - $faltas_lancadas_aluno = "SELECT fa.matricula_id, - fcc.componente_curricular_id, - fcc.quantidade, - fcc.etapa - FROM modules.falta_aluno AS fa - INNER JOIN modules.falta_componente_curricular AS fcc ON (fa.id = fcc.falta_aluno_id) - WHERE fa.matricula_id = $1 - AND fcc.componente_curricular_id = $2 - AND fcc.etapa = $3"; + LIMIT 1 + '; - $resultado = Portabilis_Utils_Database::fetchPreparedQuery($faltas_lancadas_aluno,array('params' => array($ref_cod_matricula, $ref_cod_disciplina, $etapa))); + return Portabilis_Utils_Database::selectField($sql, ['params' => [$alunoId]]) == 1; + } - return $resultado; - } + public static function getNotasLancadasAluno($ref_cod_matricula, $ref_cod_disciplina, $etapa) + { + $notas_lancadas_aluno = ' + SELECT + na.matricula_id, + ncc.componente_curricular_id, + ncc.nota, + ncc.nota_recuperacao, + ncc.nota_recuperacao_especifica, + ncc.etapa + FROM modules.nota_aluno AS na + INNER JOIN modules.nota_componente_curricular AS ncc ON (na.id = ncc.nota_aluno_id) + WHERE na.matricula_id = $1 + AND ncc.componente_curricular_id = $2 + AND ncc.etapa = $3 + '; - public static function getEscolasUser($cod_usuario) { + $resultado = Portabilis_Utils_Database::fetchPreparedQuery($notas_lancadas_aluno, ['params' => [$ref_cod_matricula, $ref_cod_disciplina, $etapa]]); - $escolas_user = "SELECT escola_usuario.ref_cod_escola AS ref_cod_escola, - coalesce(juridica.fantasia, escola_complemento.nm_escola) AS nome, - escola.ref_cod_instituicao AS instituicao - FROM pmieducar.escola_usuario - INNER JOIN pmieducar.escola ON (escola.cod_escola = escola_usuario.ref_cod_escola) - LEFT JOIN cadastro.juridica ON (juridica.idpes = escola.ref_idpes) - LEFT JOIN pmieducar.escola_complemento ON (escola_complemento.ref_cod_escola = escola.cod_escola) - WHERE escola_usuario.ref_cod_usuario = $1"; + return $resultado; + } - $resultado = Portabilis_Utils_Database::fetchPreparedQuery($escolas_user,array('params' => array($cod_usuario))); + public static function getFaltasLancadasAluno($ref_cod_matricula, $ref_cod_disciplina, $etapa) + { + $faltas_lancadas_aluno = ' + SELECT + fa.matricula_id, + fcc.componente_curricular_id, + fcc.quantidade, + fcc.etapa + FROM modules.falta_aluno AS fa + INNER JOIN modules.falta_componente_curricular AS fcc ON (fa.id = fcc.falta_aluno_id) + WHERE fa.matricula_id = $1 + AND fcc.componente_curricular_id = $2 + AND fcc.etapa = $3 + '; + + $resultado = Portabilis_Utils_Database::fetchPreparedQuery($faltas_lancadas_aluno, ['params' => [$ref_cod_matricula, $ref_cod_disciplina, $etapa]]); + + return $resultado; + } - return $resultado; + public static function getEscolasUser($cod_usuario) + { + $escolas_user = ' + SELECT + escola_usuario.ref_cod_escola AS ref_cod_escola, + coalesce(juridica.fantasia, escola_complemento.nm_escola) AS nome, + escola.ref_cod_instituicao AS instituicao + FROM pmieducar.escola_usuario + INNER JOIN pmieducar.escola ON (escola.cod_escola = escola_usuario.ref_cod_escola) + LEFT JOIN cadastro.juridica ON (juridica.idpes = escola.ref_idpes) + LEFT JOIN pmieducar.escola_complemento ON (escola_complemento.ref_cod_escola = escola.cod_escola) + WHERE escola_usuario.ref_cod_usuario = $1 + '; + + $resultado = Portabilis_Utils_Database::fetchPreparedQuery($escolas_user, ['params' => [$cod_usuario]]); + + return $resultado; + } - } + public static function usuarioNivelBibliotecaEscolar($codUsuario) + { + $permissao = new clsPermissoes(); + $nivel = $permissao->nivel_acesso($codUsuario); - public static function usuarioNivelBibliotecaEscolar($codUsuario) { - $permissao = new clsPermissoes(); - $nivel = $permissao->nivel_acesso($codUsuario); + if ($nivel == App_Model_NivelTipoUsuario::ESCOLA || + $nivel == App_Model_NivelTipoUsuario::BIBLIOTECA) { + return true; + } - if ($nivel == App_Model_NivelTipoUsuario::ESCOLA || - $nivel == App_Model_NivelTipoUsuario::BIBLIOTECA) { - return true; + return false; } - return false; - } - /** * Retorna as etapas da turma. * @@ -1284,10 +1627,9 @@ public static function usuarioNivelBibliotecaEscolar($codUsuario) { */ public static function getEtapasDaTurma($turma) { - $sql = " - - select * from ( - + $sql = ' + select * from + ( select t.cod_turma, anm.sequencial, @@ -1302,9 +1644,9 @@ public static function getEtapasDaTurma($turma) on anm.ref_ref_cod_escola = t.ref_ref_cod_escola and anm.ref_ano = t.ano where c.padrao_ano_escolar = 1 - + union all - + select t.cod_turma, tm.sequencial, @@ -1319,10 +1661,8 @@ public static function getEtapasDaTurma($turma) on tm.ref_cod_turma = t.cod_turma where c.padrao_ano_escolar = 0 ) as etapas - where cod_turma = $1; - - "; + '; return Portabilis_Utils_Database::fetchPreparedQuery($sql, [ 'params' => [$turma] @@ -1338,7 +1678,7 @@ public static function getEtapasDaTurma($turma) */ public static function getEtapa($etapaId) { - $sql = "select * from pmieducar.modulo where cod_modulo = $1;"; + $sql = 'select * from pmieducar.modulo where cod_modulo = $1;'; $query = Portabilis_Utils_Database::fetchPreparedQuery($sql, [ 'params' => [$etapaId] diff --git a/ieducar/lib/App/Model/Matricula.php b/ieducar/lib/App/Model/Matricula.php index 7e4780c6f0..c42307fa70 100644 --- a/ieducar/lib/App/Model/Matricula.php +++ b/ieducar/lib/App/Model/Matricula.php @@ -1,84 +1,54 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Entity.php'; require_once 'App/Model/MatriculaSituacao.php'; -/** - * App_Model_Matricula class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class App_Model_Matricula { - /** - * Atualiza os dados da matrícula do aluno, promovendo-o ou retendo-o. Usa - * uma instância da classe legada clsPmieducarMatricula para tal. - * - * @param int $matricula - * @param int $usuario - * @param bool $aprovado - * @return bool - */ - public static function atualizaMatricula($matricula, $usuario, $aprovado = TRUE) - { - $instance = CoreExt_Entity::addClassToStorage('clsPmieducarMatricula', NULL, - 'include/pmieducar/clsPmieducarMatricula.inc.php'); - - $instance->cod_matricula = $matricula; - $instance->ref_usuario_cad = $usuario; - $instance->ref_usuario_exc = $usuario; - - if (is_int($aprovado)) - $instance->aprovado = $aprovado; - else + /** + * Atualiza os dados da matrícula do aluno, promovendo-o ou retendo-o. Usa + * uma instância da classe legada clsPmieducarMatricula para tal. + * + * @param int $matricula + * @param int $usuario + * @param bool $aprovado + * + * @return bool + */ + public static function atualizaMatricula($matricula, $usuario, $aprovado = true) { - $instance->aprovado = ($aprovado == TRUE) ? - App_Model_MatriculaSituacao::APROVADO : - App_Model_MatriculaSituacao::REPROVADO; + $instance = CoreExt_Entity::addClassToStorage( + 'clsPmieducarMatricula', + null, + 'include/pmieducar/clsPmieducarMatricula.inc.php' + ); + + $instance->cod_matricula = $matricula; + $instance->ref_usuario_cad = $usuario; + $instance->ref_usuario_exc = $usuario; + + if (is_int($aprovado)) { + $instance->aprovado = $aprovado; + } else { + $instance->aprovado = $aprovado == true + ? App_Model_MatriculaSituacao::APROVADO + : App_Model_MatriculaSituacao::REPROVADO; + } + + return $instance->edita(); } - return $instance->edita(); - } - public static function setNovaSituacao($matricula, $novaSituacao){ - $instance = CoreExt_Entity::addClassToStorage('clsPmieducarMatricula', NULL, - 'include/pmieducar/clsPmieducarMatricula.inc.php'); + public static function setNovaSituacao($matricula, $novaSituacao) + { + $instance = CoreExt_Entity::addClassToStorage( + 'clsPmieducarMatricula', + null, + 'include/pmieducar/clsPmieducarMatricula.inc.php' + ); - $instance->cod_matricula = $matricula; - $instance->aprovado = $novaSituacao; + $instance->cod_matricula = $matricula; + $instance->aprovado = $novaSituacao; - return $instance->edita(); - } + return $instance->edita(); + } } diff --git a/ieducar/lib/App/Model/MatriculaSituacao.php b/ieducar/lib/App/Model/MatriculaSituacao.php index d65894008b..e04c83986b 100644 --- a/ieducar/lib/App/Model/MatriculaSituacao.php +++ b/ieducar/lib/App/Model/MatriculaSituacao.php @@ -1,85 +1,49 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Enum.php'; -/** - * App_Model_MatriculaSituacao class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class App_Model_MatriculaSituacao extends CoreExt_Enum { - const APROVADO = 1; - const REPROVADO = 2; - const EM_ANDAMENTO = 3; - const TRANSFERIDO = 4; - const RECLASSIFICADO = 5; - const ABANDONO = 6; - const EM_EXAME = 7; - const APROVADO_APOS_EXAME = 8; - const APROVADO_SEM_EXAME = 10; - const PRE_MATRICULA = 11; - const APROVADO_COM_DEPENDENCIA = 12; - const APROVADO_PELO_CONSELHO = 13; - const REPROVADO_POR_FALTAS = 14; - const FALECIDO = 15; + const APROVADO = 1; + const REPROVADO = 2; + const EM_ANDAMENTO = 3; + const TRANSFERIDO = 4; + const RECLASSIFICADO = 5; + const ABANDONO = 6; + const EM_EXAME = 7; + const APROVADO_APOS_EXAME = 8; + const APROVADO_SEM_EXAME = 10; + const PRE_MATRICULA = 11; + const APROVADO_COM_DEPENDENCIA = 12; + const APROVADO_PELO_CONSELHO = 13; + const REPROVADO_POR_FALTAS = 14; + const FALECIDO = 15; + + protected $_data = [ + self::APROVADO => 'Aprovado', + self::REPROVADO => 'Retido', + self::EM_ANDAMENTO => 'Cursando', + self::TRANSFERIDO => 'Transferido', + self::RECLASSIFICADO => 'Reclassificado', + self::ABANDONO => 'Abandono', + self::EM_EXAME => 'Em exame', + self::APROVADO_APOS_EXAME => 'Aprovado após exame', + self::PRE_MATRICULA => 'Pré-matrícula', + self::APROVADO_COM_DEPENDENCIA => 'Aprovado com dependência', + self::APROVADO_PELO_CONSELHO => 'Aprovado pelo conselho', + self::REPROVADO_POR_FALTAS => 'Reprovado por faltas', + self::FALECIDO => 'Falecido' + ]; - protected $_data = array( - self::APROVADO => 'Aprovado', - self::REPROVADO => 'Retido', - self::EM_ANDAMENTO => 'Cursando', - self::TRANSFERIDO => 'Transferido', - self::RECLASSIFICADO => 'Reclassificado', - self::ABANDONO => 'Abandono', - self::EM_EXAME => 'Em exame', - self::APROVADO_APOS_EXAME => 'Aprovado após exame', - self::PRE_MATRICULA => 'Pré-matrícula', - self::APROVADO_COM_DEPENDENCIA => 'Aprovado com dependência', - self::APROVADO_PELO_CONSELHO => 'Aprovado pelo conselho', - self::REPROVADO_POR_FALTAS => 'Reprovado por faltas', - self::FALECIDO => 'Falecido' - ); + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } + public static function getSituacao($id) + { + $instance = self::getInstance()->_data; - public static function getSituacao($id) { - $instance = self::getInstance()->_data; - return $instance[$id]; - } + return $instance[$id]; + } } diff --git a/ieducar/lib/App/Model/NivelAcesso.php b/ieducar/lib/App/Model/NivelAcesso.php index c4cbde5f7d..1a239c0672 100644 --- a/ieducar/lib/App/Model/NivelAcesso.php +++ b/ieducar/lib/App/Model/NivelAcesso.php @@ -1,33 +1,5 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Enum.php'; /** @@ -54,32 +26,23 @@ * * Onde, T = TRUE; F = FALSE * - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @see clsPermissoes#permissao_cadastra - * @see clsPermissoes#permissao_excluir - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ */ class App_Model_NivelAcesso extends CoreExt_Enum { - const POLI_INSTITUCIONAL = 1; - const INSTITUCIONAL = 3; - const SOMENTE_ESCOLA = 7; - const SOMENTE_BIBLIOTECA = 11; + const POLI_INSTITUCIONAL = 1; + const INSTITUCIONAL = 3; + const SOMENTE_ESCOLA = 7; + const SOMENTE_BIBLIOTECA = 11; - protected $_data = array( - self::POLI_INSTITUCIONAL => 'Poli-institucional', - self::INSTITUCIONAL => 'Institucional', - self::SOMENTE_ESCOLA => 'Somente escola', - self::SOMENTE_BIBLIOTECA => 'Somente biblioteca' - ); + protected $_data = [ + self::POLI_INSTITUCIONAL => 'Poli-institucional', + self::INSTITUCIONAL => 'Institucional', + self::SOMENTE_ESCOLA => 'Somente escola', + self::SOMENTE_BIBLIOTECA => 'Somente biblioteca' + ]; - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } -} \ No newline at end of file + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } +} diff --git a/ieducar/lib/App/Model/NivelTipoUsuario.php b/ieducar/lib/App/Model/NivelTipoUsuario.php index ac98dd5360..fd7bfbb6a7 100644 --- a/ieducar/lib/App/Model/NivelTipoUsuario.php +++ b/ieducar/lib/App/Model/NivelTipoUsuario.php @@ -1,61 +1,23 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Enum.php'; -/** - * App_Model_NivelTipoUsuario class. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class App_Model_NivelTipoUsuario extends CoreExt_Enum { - const POLI_INSTITUCIONAL = 1; - const INSTITUCIONAL = 2; - const ESCOLA = 4; - const BIBLIOTECA = 8; + const POLI_INSTITUCIONAL = 1; + const INSTITUCIONAL = 2; + const ESCOLA = 4; + const BIBLIOTECA = 8; - protected $_data = array( - self::POLI_INSTITUCIONAL => 'Poli-institucional', - self::INSTITUCIONAL => 'Institucional', - self::ESCOLA => 'Escola', - self::BIBLIOTECA => 'Biblioteca' - ); + protected $_data = [ + self::POLI_INSTITUCIONAL => 'Poli-institucional', + self::INSTITUCIONAL => 'Institucional', + self::ESCOLA => 'Escola', + self::BIBLIOTECA => 'Biblioteca' + ]; - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } -} \ No newline at end of file + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } +} diff --git a/ieducar/lib/App/Model/Pais.php b/ieducar/lib/App/Model/Pais.php index 2bfc875416..2558908219 100644 --- a/ieducar/lib/App/Model/Pais.php +++ b/ieducar/lib/App/Model/Pais.php @@ -2,5 +2,5 @@ class App_Model_Pais { - const BRASIL = 45; -} \ No newline at end of file + const BRASIL = 45; +} diff --git a/ieducar/lib/App/Model/Servidor.php b/ieducar/lib/App/Model/Servidor.php index 33360d3859..0ac70a3636 100644 --- a/ieducar/lib/App/Model/Servidor.php +++ b/ieducar/lib/App/Model/Servidor.php @@ -6,4 +6,4 @@ class Servidor { const SITUACAO_CURSO_SUPERIOR_CONCLUIDO = 1; const SITUACAO_CURSO_SUPERIOR_CURSANDO = 2; -} \ No newline at end of file +} diff --git a/ieducar/lib/App/Model/SimNao.php b/ieducar/lib/App/Model/SimNao.php index c36ab46839..c63ff90b88 100644 --- a/ieducar/lib/App/Model/SimNao.php +++ b/ieducar/lib/App/Model/SimNao.php @@ -1,57 +1,19 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.2.0 - * @version $Id$ - */ - require_once 'CoreExt/Enum.php'; -/** - * App_Model_SimNao class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Classe disponível desde a versão 1.2.0 - * @version @@package_version@@ - */ class App_Model_SimNao extends CoreExt_Enum { - const NAO = 0; - const SIM = 1; + const NAO = 0; + const SIM = 1; - protected $_data = array( - self::NAO => 'Não', - self::SIM => 'Sim' - ); + protected $_data = [ + self::NAO => 'Não', + self::SIM => 'Sim' + ]; - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } -} \ No newline at end of file + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } +} diff --git a/ieducar/lib/App/Model/TipoDiaMotivo.php b/ieducar/lib/App/Model/TipoDiaMotivo.php index 42fdf8ea9f..5da381654b 100644 --- a/ieducar/lib/App/Model/TipoDiaMotivo.php +++ b/ieducar/lib/App/Model/TipoDiaMotivo.php @@ -1,59 +1,21 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.2.0 - * @version $Id$ - */ - require_once 'CoreExt/Enum.php'; -/** - * App_Model_TipoDiaMotivo class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Classe disponível desde a versão 1.2.0 - * @version @@package_version@@ - */ class App_Model_TipoDiaMotivo extends CoreExt_Enum { - const DIA_LETIVO = 'l'; - const DIA_NAO_LETIVO = 'n'; - const DIA_EXTRA_LETIVO = 'e'; + const DIA_LETIVO = 'l'; + const DIA_NAO_LETIVO = 'n'; + const DIA_EXTRA_LETIVO = 'e'; - protected $_data = array( - self::DIA_LETIVO => 'Dia letivo', - self::DIA_NAO_LETIVO => 'Dia não letivo', - self::DIA_EXTRA_LETIVO => 'Dia extra letivo', - ); + protected $_data = [ + self::DIA_LETIVO => 'Dia letivo', + self::DIA_NAO_LETIVO => 'Dia não letivo', + self::DIA_EXTRA_LETIVO => 'Dia extra letivo', + ]; - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } -} \ No newline at end of file + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } +} diff --git a/ieducar/lib/App/Model/ZonaLocalizacao.php b/ieducar/lib/App/Model/ZonaLocalizacao.php index c9eb329583..e9d75a6fdb 100644 --- a/ieducar/lib/App/Model/ZonaLocalizacao.php +++ b/ieducar/lib/App/Model/ZonaLocalizacao.php @@ -1,57 +1,19 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Arquivo disponível desde a versão 1.2.0 - * @version $Id$ - */ - require_once 'CoreExt/Enum.php'; -/** - * App_Model_ZonaLocalizacao class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package App_Model - * @since Classe disponível desde a versão 1.2.0 - * @version @@package_version@@ - */ class App_Model_ZonaLocalizacao extends CoreExt_Enum { - const URBANA = 1; - const RURAL = 2; + const URBANA = 1; + const RURAL = 2; - protected $_data = array( - self::URBANA => 'Urbana', - self::RURAL => 'Rural' - ); + protected $_data = [ + self::URBANA => 'Urbana', + self::RURAL => 'Rural' + ]; - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } -} \ No newline at end of file + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } +} diff --git a/ieducar/lib/App/Unificacao/Aluno.php b/ieducar/lib/App/Unificacao/Aluno.php index 7c9b5e25ef..1ca78c16c4 100644 --- a/ieducar/lib/App/Unificacao/Aluno.php +++ b/ieducar/lib/App/Unificacao/Aluno.php @@ -4,26 +4,40 @@ class App_Unificacao_Aluno { - public static function unifica($codAlunoPrincipal, $codAlunos, $codPessoa, clsBanco $db) { self::validaParametros($codAlunoPrincipal, $codAlunos, $codPessoa); - $codAlunos = implode(",", $codAlunos); - - $db->consulta("UPDATE pmieducar.historico_escolar - SET ref_cod_aluno = {$codAlunoPrincipal}, - sequencial = he.seq+he.max_seq - FROM - (SELECT ref_cod_aluno AS aluno, - sequencial AS seq, - COALESCE((SELECT max(sequencial) - FROM pmieducar.historico_escolar - WHERE ref_cod_aluno = {$codAlunoPrincipal}),0) AS max_seq - FROM pmieducar.historico_escolar - WHERE ref_cod_aluno IN ({$codAlunos})) AS he - WHERE sequencial = he.seq - AND ref_cod_aluno = he.aluno"); + $codAlunos = implode(',', $codAlunos); + + $db->consulta( + " + UPDATE pmieducar.historico_escolar + SET + ref_cod_aluno = {$codAlunoPrincipal}, + sequencial = he.seq+he.max_seq + FROM + ( + SELECT + ref_cod_aluno AS aluno, + sequencial AS seq, + COALESCE + ( + ( + SELECT max(sequencial) + FROM pmieducar.historico_escolar + WHERE ref_cod_aluno = {$codAlunoPrincipal} + ), + 0 + ) AS max_seq + FROM pmieducar.historico_escolar + WHERE ref_cod_aluno IN ({$codAlunos}) + ) AS he + WHERE sequencial = he.seq + AND ref_cod_aluno = he.aluno + " + ); + $db->consulta("UPDATE pmieducar.matricula SET ref_cod_aluno = {$codAlunoPrincipal} where ref_cod_aluno in ({$codAlunos})"); $db->consulta("UPDATE pmieducar.aluno SET ativo = 0, data_exclusao = now(), ref_usuario_exc = {$codPessoa} where cod_aluno in ({$codAlunos})"); @@ -35,9 +49,11 @@ private static function validaParametros($codAlunoPrincipal, $codAlunos, $codPes if (!is_integer($codAlunoPrincipal)) { throw new CoreExt_Exception('Parâmetro $codAlunoPrincipal deve ser um inteiro'); } + if (!is_array($codAlunos) || !count($codAlunos)) { throw new CoreExt_Exception('Parâmetro $codAlunos deve ser um array de códigos de alunos'); } + if (!is_integer($codPessoa)) { throw new CoreExt_Exception('Parâmetro $codPessoa deve ser um inteiro'); } diff --git a/ieducar/lib/App/Unificacao/Base.php b/ieducar/lib/App/Unificacao/Base.php index 751c9d3622..5745713913 100644 --- a/ieducar/lib/App/Unificacao/Base.php +++ b/ieducar/lib/App/Unificacao/Base.php @@ -2,16 +2,16 @@ class App_Unificacao_Base { - protected $chavesManterPrimeiroVinculo = array(); - protected $chavesManterTodosVinculos = array(); - protected $chavesDeletarDuplicados = array(); + protected $chavesManterPrimeiroVinculo = []; + protected $chavesManterTodosVinculos = []; + protected $chavesDeletarDuplicados = []; protected $codigoUnificador; protected $codigosDuplicados; protected $codPessoaLogada; protected $db; protected $transacao; - public function __construct($codigoUnificador, $codigosDuplicados, $codPessoaLogada, clsBanco $db, $transacao = TRUE) + public function __construct($codigoUnificador, $codigosDuplicados, $codPessoaLogada, clsBanco $db, $transacao = true) { $this->codigoUnificador = $codigoUnificador; $this->codigosDuplicados = $codigosDuplicados; @@ -23,9 +23,11 @@ public function __construct($codigoUnificador, $codigosDuplicados, $codPessoaLog public function unifica() { $this->validaParametros(); + if ($this->transacao) { $db->begin(); } + $this->desabilitaTodasTriggers(); $this->processaChavesDeletarDuplicados(); $this->processaChavesManterTodosVinculos(); @@ -39,32 +41,40 @@ public function unifica() protected function processaChavesDeletarDuplicados() { - $stringCodigosDuplicados = implode(',',$this->codigosDuplicados); + $stringCodigosDuplicados = implode(',', $this->codigosDuplicados); + foreach ($this->chavesDeletarDuplicados as $key => $value) { try { - $this->db->Consulta(" - UPDATE {$value['tabela']} - SET {$value['coluna']} = {$this->codigoUnificador} - WHERE {$value['coluna']} IN ({$stringCodigosDuplicados}) - "); + $this->db->Consulta( + " + UPDATE {$value['tabela']} + SET {$value['coluna']} = {$this->codigoUnificador} + WHERE {$value['coluna']} IN ({$stringCodigosDuplicados}) + " + ); } catch (Exception $e) { - $this->db->Consulta(" - DELETE FROM {$value['tabela']} - WHERE {$value['coluna']} IN ({$stringCodigosDuplicados}) - "); + $this->db->Consulta( + " + DELETE FROM {$value['tabela']} + WHERE {$value['coluna']} IN ({$stringCodigosDuplicados}) + " + ); } } } protected function processaChavesManterTodosVinculos() { - $stringCodigosDuplicados = implode(',',$this->codigosDuplicados); + $stringCodigosDuplicados = implode(',', $this->codigosDuplicados); + foreach ($this->chavesManterTodosVinculos as $key => $value) { - $this->db->Consulta(" - UPDATE {$value['tabela']} + $this->db->Consulta( + " + UPDATE {$value['tabela']} SET {$value['coluna']} = {$this->codigoUnificador} WHERE {$value['coluna']} IN ({$stringCodigosDuplicados}) - "); + " + ); } } @@ -73,30 +83,37 @@ protected function processaChavesManterPrimeiroVinculo() $chavesConsultar = $this->codigosDuplicados; $chavesConsultar[] = $this->codigoUnificador; $chavesConsultarString = implode(',', $chavesConsultar); + foreach ($this->chavesManterPrimeiroVinculo as $key => $value) { - $this->db->Consulta(" - DELETE FROM {$value['tabela']} - WHERE {$value['coluna']} <> - ( - SELECT {$value['coluna']} - from {$value['tabela']} - WHERE {$value['coluna']} in ({$chavesConsultarString}) - ORDER BY {$value['coluna']} = {$this->codigoUnificador} DESC - LIMIT 1 ) - AND {$value['coluna']} in ({$chavesConsultarString}) - "); - $this->db->Consulta(" - UPDATE {$value['tabela']} - SET {$value['coluna']} = {$this->codigoUnificador} - WHERE {$value['coluna']} IN ({$chavesConsultarString}) - "); + $this->db->Consulta( + " + DELETE FROM {$value['tabela']} + WHERE {$value['coluna']} <> + ( + SELECT {$value['coluna']} + from {$value['tabela']} + WHERE {$value['coluna']} in ({$chavesConsultarString}) + ORDER BY {$value['coluna']} = {$this->codigoUnificador} DESC + LIMIT 1 + ) + AND {$value['coluna']} in ({$chavesConsultarString}) + " + ); + + $this->db->Consulta( + " + UPDATE {$value['tabela']} + SET {$value['coluna']} = {$this->codigoUnificador} + WHERE {$value['coluna']} IN ({$chavesConsultarString}) + " + ); } } protected function tabelasEnvolvidas() { $todasChaves = array_merge($this->chavesManterPrimeiroVinculo, $this->chavesManterTodosVinculos); - $todasTabelas = array(); + $todasTabelas = []; foreach ($todasChaves as $key => $value) { $todasTabelas[$value['tabela']] = $value['tabela']; @@ -108,6 +125,7 @@ protected function tabelasEnvolvidas() protected function desabilitaTodasTriggers() { $tabelasEnvolvidas = $this->tabelasEnvolvidas(); + foreach ($tabelasEnvolvidas as $key => $tabela) { $this->db->Consulta("ALTER TABLE {$tabela} DISABLE TRIGGER ALL"); } @@ -116,6 +134,7 @@ protected function desabilitaTodasTriggers() protected function habilitaTodasTriggers() { $tabelasEnvolvidas = $this->tabelasEnvolvidas(); + foreach ($tabelasEnvolvidas as $key => $tabela) { $this->db->Consulta("ALTER TABLE {$tabela} ENABLE TRIGGER ALL"); } @@ -123,14 +142,16 @@ protected function habilitaTodasTriggers() protected function validaParametros() { - if ($this->codigoUnificador != (int) $this->codigoUnificador ) { + if ($this->codigoUnificador != (int) $this->codigoUnificador) { throw new CoreExt_Exception('Parâmetro 1 deve ser o código unificador'); } + if (!is_array($this->codigosDuplicados) || !count($this->codigosDuplicados)) { throw new CoreExt_Exception('Parâmetro 2 deve ser um array de códigos duplicados'); } + if ($this->codPessoaLogada != (int) $this->codPessoaLogada) { throw new CoreExt_Exception('Parâmetro 3 deve ser um inteiro'); } } -} \ No newline at end of file +} diff --git a/ieducar/lib/App/Unificacao/Cliente.php b/ieducar/lib/App/Unificacao/Cliente.php index ab537891f7..361db8ce4f 100644 --- a/ieducar/lib/App/Unificacao/Cliente.php +++ b/ieducar/lib/App/Unificacao/Cliente.php @@ -7,31 +7,31 @@ class App_Unificacao_Cliente extends App_Unificacao_Base { protected $chavesManterPrimeiroVinculo = [ [ - 'tabela' => 'pmieducar.cliente', - 'coluna' => 'cod_cliente' + 'tabela' => 'pmieducar.cliente', + 'coluna' => 'cod_cliente' ], [ - 'tabela' => 'pmieducar.cliente_suspensao', - 'coluna' => 'ref_cod_cliente' + 'tabela' => 'pmieducar.cliente_suspensao', + 'coluna' => 'ref_cod_cliente' ], [ - 'tabela' => 'pmieducar.cliente_tipo_cliente', - 'coluna' => 'ref_cod_cliente' + 'tabela' => 'pmieducar.cliente_tipo_cliente', + 'coluna' => 'ref_cod_cliente' ] ]; protected $chavesManterTodosVinculos = [ [ - 'tabela' => 'pmieducar.exemplar_emprestimo', - 'coluna' => 'ref_cod_cliente' + 'tabela' => 'pmieducar.exemplar_emprestimo', + 'coluna' => 'ref_cod_cliente' ], [ - 'tabela' => 'pmieducar.pagamento_multa', - 'coluna' => 'ref_cod_cliente' + 'tabela' => 'pmieducar.pagamento_multa', + 'coluna' => 'ref_cod_cliente' ], [ - 'tabela' => 'pmieducar.reservas', - 'coluna' => 'ref_cod_cliente' + 'tabela' => 'pmieducar.reservas', + 'coluna' => 'ref_cod_cliente' ], ]; } diff --git a/ieducar/lib/App/Unificacao/Pessoa.php b/ieducar/lib/App/Unificacao/Pessoa.php index 4cf2488f2d..fb8d3b1f71 100644 --- a/ieducar/lib/App/Unificacao/Pessoa.php +++ b/ieducar/lib/App/Unificacao/Pessoa.php @@ -8,595 +8,594 @@ class App_Unificacao_Pessoa extends App_Unificacao_Base { - - protected $chavesManterPrimeiroVinculo = array( - array( + protected $chavesManterPrimeiroVinculo = [ + [ 'tabela' => 'cadastro.fisica_deficiencia', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica_raca', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica_cpf', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica_foto', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.endereco_pessoa', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.fone_pessoa', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.documento', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.endereco_externo', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.pessoa', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'pmieducar.biblioteca_usuario', 'coluna' => 'ref_cod_usuario' - ), - array( + ], + [ 'tabela' => 'pmieducar.escola_usuario', 'coluna' => 'ref_cod_usuario' - ), - array( + ], + [ 'tabela' => 'pmieducar.usuario', 'coluna' => 'cod_usuario' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica_sangue', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'modules.pessoa_transporte', 'coluna' => 'cod_pessoa_transporte' - ), - array( + ], + [ 'tabela' => 'pmieducar.aluno', 'coluna' => 'ref_idpes' - ), - ); + ], + ]; - protected $chavesManterTodosVinculos = array( - array( + protected $chavesManterTodosVinculos = [ + [ 'tabela' => 'acesso.usuario', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'acesso.usuario', 'coluna' => 'idpes_sga' - ), - array( + ], + [ 'tabela' => 'acesso.log_acesso', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'acesso.log_erro', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'acesso.pessoa_instituicao', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'alimentos.cliente', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'alimentos.pessoa', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.aviso_nome', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica', 'coluna' => 'idpes_mae' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica', 'coluna' => 'idpes_pai' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica', 'coluna' => 'idpes_responsavel' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica', 'coluna' => 'idpes_con' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica_cpf', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.fisica_cpf', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.fone_pessoa', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.fone_pessoa', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.endereco_pessoa', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.endereco_pessoa', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.raca', 'coluna' => 'idpes_exc' - ), - array( + ], + [ 'tabela' => 'cadastro.raca', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.socio', 'coluna' => 'idpes_juridica' - ), - array( + ], + [ 'tabela' => 'cadastro.socio', 'coluna' => 'idpes_fisica' - ), - array( + ], + [ 'tabela' => 'cadastro.socio', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.socio', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.juridica', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.juridica', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.juridica', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.religiao', 'coluna' => 'idpes_exc' - ), - array( + ], + [ 'tabela' => 'cadastro.religiao', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.cep_logradouro_bairro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.cep_logradouro_bairro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.bairro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.bairro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.cep_logradouro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.cep_logradouro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.documento', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.documento', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.documento', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.endereco_externo', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.endereco_externo', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.endereco_externo', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.endereco_pessoa', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.endereco_pessoa', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.endereco_pessoa', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.fisica', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.fisica', 'coluna' => 'idpes_mae' - ), - array( + ], + [ 'tabela' => 'historico.fisica', 'coluna' => 'idpes_pai' - ), - array( + ], + [ 'tabela' => 'historico.fisica', 'coluna' => 'idpes_responsavel' - ), - array( + ], + [ 'tabela' => 'historico.fisica', 'coluna' => 'idpes_con' - ), - array( + ], + [ 'tabela' => 'historico.fisica', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.fisica', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.pessoa', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.pessoa', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.pessoa', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.fisica_cpf', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.fisica_cpf', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.fisica_cpf', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.fone_pessoa', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.fone_pessoa', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.fone_pessoa', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.funcionario', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.funcionario', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.funcionario', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.juridica', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'historico.juridica', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.juridica', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.logradouro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.logradouro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.socio', 'coluna' => 'idpes_juridica' - ), - array( + ], + [ 'tabela' => 'historico.socio', 'coluna' => 'idpes_fisica' - ), - array( + ], + [ 'tabela' => 'historico.socio', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.socio', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'historico.municipio', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'historico.municipio', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'modules.motorista', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'modules.empresa_transporte_escolar', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'modules.empresa_transporte_escolar', 'coluna' => 'ref_resp_idpes' - ), - array( + ], + [ 'tabela' => 'modules.pessoa_transporte', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'modules.pessoa_transporte', 'coluna' => 'ref_idpes_destino' - ), - array( + ], + [ 'tabela' => 'pmieducar.cliente', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'pmieducar.responsaveis_aluno', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'pmiotopic.grupopessoa', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'pmiotopic.topico', 'coluna' => 'ref_idpes_cad' - ), - array( + ], + [ 'tabela' => 'pmiotopic.topico', 'coluna' => 'ref_idpes_exc' - ), - array( + ], + [ 'tabela' => 'pmiotopic.notas', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'public.distrito', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'public.distrito', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'urbano.cep_logradouro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'urbano.cep_logradouro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'urbano.cep_logradouro_bairro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'urbano.cep_logradouro_bairro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'alimentos.unidade_atendida', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'alimentos.fornecedor', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.funcionario', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.funcionario', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.funcionario', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.historico_cartao', 'coluna' => 'idpes_cidadao' - ), - array( + ], + [ 'tabela' => 'cadastro.historico_cartao', 'coluna' => 'idpes_emitiu' - ), - array( + ], + [ 'tabela' => 'cadastro.documento', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.documento', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'modules.rota_transporte_escolar', 'coluna' => 'ref_idpes_destino' - ), - array( + ], + [ 'tabela' => 'pmidrh.setor', 'coluna' => 'ref_idpes_resp' - ), - array( + ], + [ 'tabela' => 'pmieducar.escola', 'coluna' => 'ref_idpes' - ), - array( + ], + [ 'tabela' => 'pmieducar.escola', 'coluna' => 'ref_idpes_gestor' - ), - array( + ], + [ 'tabela' => 'pmieducar.escola', 'coluna' => 'ref_idpes_secretario_escolar' - ), - array( + ], + [ 'tabela' => 'pmiotopic.participante', 'coluna' => 'ref_ref_idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.endereco_externo', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'cadastro.endereco_externo', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.pessoa', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'cadastro.pessoa', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'public.bairro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'public.bairro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'public.logradouro', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'public.logradouro', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'public.municipio', 'coluna' => 'idpes_rev' - ), - array( + ], + [ 'tabela' => 'public.municipio', 'coluna' => 'idpes_cad' - ), - array( + ], + [ 'tabela' => 'pmicontrolesis.foto_evento', 'coluna' => 'ref_ref_cod_pessoa_fj' - ), - array( + ], + [ 'tabela' => 'pmieducar.candidato_reserva_vaga', 'coluna' => 'ref_cod_pessoa_cad' - ), - array( + ], + [ 'tabela' => 'pmieducar.candidato_fila_unica', 'coluna' => 'ref_cod_pessoa_cad' - ), - array( + ], + [ 'tabela' => 'pmieducar.candidato_fila_unica', 'coluna' => 'ref_cod_pessoa_exc' - ), - array( + ], + [ 'tabela' => 'pmiotopic.funcionario_su', 'coluna' => 'ref_ref_cod_pessoa_fj' - ), - array( + ], + [ 'tabela' => 'pmiotopic.grupomoderador', 'coluna' => 'ref_ref_cod_pessoa_fj' - ), - array( + ], + [ 'tabela' => 'portal.acesso', 'coluna' => 'cod_pessoa' - ), - array( + ], + [ 'tabela' => 'portal.agenda_compromisso', 'coluna' => 'ref_ref_cod_pessoa_cad' - ), - array( + ], + [ 'tabela' => 'portal.agenda_responsavel', 'coluna' => 'ref_ref_cod_pessoa_fj' - ), - ); + ], + ]; - protected $chavesDeletarDuplicados = array( - array( + protected $chavesDeletarDuplicados = [ + [ 'tabela' => 'consistenciacao.historico_campo', 'coluna' => 'idpes' - ), - array( + ], + [ 'tabela' => 'cadastro.pessoa_fonetico', 'coluna' => 'idpes' - ) - ); + ] + ]; public function unifica() { @@ -612,7 +611,8 @@ protected function unificaClientes() $chavesConsultar[] = $this->codigoUnificador; $chavesConsultarString = implode(',', $chavesConsultar); - $this->db->consulta(" + $this->db->consulta( + " SELECT cod_cliente FROM pmieducar.cliente WHERE ref_idpes in ({$chavesConsultarString}) @@ -626,7 +626,7 @@ protected function unificaClientes() $codigoClientes[] = $reg['cod_cliente']; } if (COUNT($codigoClientes) < 2) { - return TRUE; + return true; } $unificadorCliente = new App_Unificacao_Cliente(array_shift($codigoClientes), $codigoClientes, $this->codPessoaLogada, $this->db, $this->transacao); $unificadorCliente->unifica(); @@ -635,7 +635,7 @@ protected function unificaClientes() protected function validaParametros() { parent::validaParametros(); - $pessoas = implode(",", (array_merge(array($this->codigoUnificador),$this->codigosDuplicados))); + $pessoas = implode(',', (array_merge([$this->codigoUnificador], $this->codigosDuplicados))); $numeroAlunos = $this->db->CampoUnico("SELECT count(*) numero_alunos FROM pmieducar.aluno where ref_idpes IN ({$pessoas}) AND ativo = 1 "); if ($numeroAlunos > 1) { throw new CoreExt_Exception('Não é permitido unificar mais de uma pessoa vinculada com alunos. Efetue primeiro a unificação de alunos e tente novamente.'); diff --git a/ieducar/lib/App/Unificacao/Servidor.php b/ieducar/lib/App/Unificacao/Servidor.php index e9e60775b7..3dc3ce101e 100644 --- a/ieducar/lib/App/Unificacao/Servidor.php +++ b/ieducar/lib/App/Unificacao/Servidor.php @@ -5,68 +5,68 @@ class App_Unificacao_Servidor extends App_Unificacao_Base { - protected $chavesManterPrimeiroVinculo = array( - array( + protected $chavesManterPrimeiroVinculo = [ + [ 'tabela' => 'pmieducar.servidor', 'coluna' => 'cod_servidor' - ), - array( + ], + [ 'tabela' => 'modules.educacenso_cod_docente', 'coluna' => 'cod_servidor' - ), - ); + ], + ]; - protected $chavesManterTodosVinculos = array( - array( + protected $chavesManterTodosVinculos = [ + [ 'tabela' => 'pmieducar.avaliacao_desempenho', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'pmieducar.falta_atraso', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'pmieducar.falta_atraso_compensado', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'pmieducar.servidor_formacao', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'pmieducar.servidor_afastamento', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'pmieducar.servidor_alocacao', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'pmieducar.servidor_funcao', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'modules.professor_turma', 'coluna' => 'servidor_id' - ), - array( + ], + [ 'tabela' => 'modules.docente_licenciatura', 'coluna' => 'servidor_id' - ), - array( + ], + [ 'tabela' => 'pmieducar.turma', 'coluna' => 'ref_cod_regente' - ), - ); + ], + ]; - protected $chavesDeletarDuplicados = array( - array( + protected $chavesDeletarDuplicados = [ + [ 'tabela' => 'pmieducar.servidor_curso_ministra', 'coluna' => 'ref_cod_servidor' - ), - array( + ], + [ 'tabela' => 'pmieducar.servidor_disciplina', 'coluna' => 'ref_cod_servidor' - ), - ); + ], + ]; } diff --git a/ieducar/lib/Core/Controller/Page/Abstract.php b/ieducar/lib/Core/Controller/Page/Abstract.php index f81dd4c482..04fc210cdd 100644 --- a/ieducar/lib/Core/Controller/Page/Abstract.php +++ b/ieducar/lib/Core/Controller/Page/Abstract.php @@ -1,464 +1,513 @@ NULL, - 'new_success' => 'index', - 'new_success_params' => array(), - 'edit_success' => 'view', - 'edit_success_params' => array(), - 'delete_success' => 'index', - 'delete_success_params' => array(), - 'url_cancelar' => NULL, - ); - - /** - * Coleção de mensagens de erros retornados pelos validadores de - * CoreExt_Entity. - * @var array - */ - protected $_errors = array(); - - /** - * Instância de Core_View - * @var Core_View - */ - protected $_view = NULL; - - /** - * Instância de CoreExt_DataMapper - * @var CoreExt_DataMapper - */ - protected $_dataMapper = NULL; - - /** - * Instância de CoreExt_Entity - * @var CoreExt_Entity - */ - protected $_entity = NULL; - - /** - * Identificador do número de processo para verificação de autorização. - * @see clsBase#verificaPermissao() - * @var int - */ - protected $_processoAp = NULL; - - /** - * Título a ser utilizado na barra de título. - * @see clsBase#MakeHeadHtml() - * @var string - */ - protected $_titulo = NULL; - - /** - * Array com labels para botões, inseridos no HTML via RenderHTML(). Marcado - * como public para manter compatibilidade com as classes cls(Cadastro|Detalhe| - * Listagem) que acessam o array diretamente. - * @var array|NULL - */ - public $array_botao = NULL; - - /** - * Array com labels para botões, inseridos no HTML via RenderHTML(). Marcado - * como public para manter compatibilidade com as classes cls(Cadastro|Detalhe| - * Listagem) que acessam o array diretamente. - * @var array|NULL - */ - public $array_botao_url = NULL; - - /** - * @var string - */ - public $url_cancelar = NULL; - - /** - * @var array - */ - private $_output = array(); - - /** - * @var integer - */ - public $pessoa_logada = NULL; - - /** - * @var string - */ - public $locale = NULL; - - /** - * Construtor. - */ - public function __construct() - { - $this->_options['id_usuario'] = $this->getSession()->id_pessoa; - $this->pessoa_logada = $this->getSession()->id_pessoa ?? null; - } - - /** - * @see CoreExt_Configurable#setOptions($options) - */ - public function setOptions(array $options = array()) - { - $options = array_change_key_case($options, CASE_LOWER); - - if (isset($options['datamapper'])) { - $this->setDataMapper($options['datamapper']); - unset($options['datamapper']); + /** + * Opções de configuração geral da classe. + * + * @var array + */ + protected $_options = [ + 'id_usuario' => null, + 'new_success' => 'index', + 'new_success_params' => [], + 'edit_success' => 'view', + 'edit_success_params' => [], + 'delete_success' => 'index', + 'delete_success_params' => [], + 'url_cancelar' => null, + ]; + + /** + * Coleção de mensagens de erros retornados pelos validadores de + * CoreExt_Entity. + * + * @var array + */ + protected $_errors = []; + + /** + * Instância de Core_View + * + * @var Core_View + */ + protected $_view = null; + + /** + * Instância de CoreExt_DataMapper + * + * @var CoreExt_DataMapper + */ + protected $_dataMapper = null; + + /** + * Instância de CoreExt_Entity + * + * @var CoreExt_Entity + */ + protected $_entity = null; + + /** + * Identificador do número de processo para verificação de autorização. + * + * @see clsBase::verificaPermissao() + * + * @var int + */ + protected $_processoAp = null; + + /** + * Título a ser utilizado na barra de título. + * + * @see clsBase::MakeHeadHtml() + * + * @var string + */ + protected $_titulo = null; + + /** + * Array com labels para botões, inseridos no HTML via RenderHTML(). Marcado + * como public para manter compatibilidade com as classes cls(Cadastro|Detalhe| + * Listagem) que acessam o array diretamente. + * + * @var array|NULL + */ + public $array_botao = null; + + /** + * Array com labels para botões, inseridos no HTML via RenderHTML(). Marcado + * como public para manter compatibilidade com as classes cls(Cadastro|Detalhe| + * Listagem) que acessam o array diretamente. + * + * @var array|NULL + */ + public $array_botao_url = null; + + /** + * @var string + */ + public $url_cancelar = null; + + /** + * @var array + */ + private $_output = []; + + /** + * @var integer + */ + public $pessoa_logada = null; + + /** + * @var string + */ + public $locale = null; + + /** + * Construtor. + */ + public function __construct() + { + $this->_options['id_usuario'] = $this->getSession()->id_pessoa; + $this->pessoa_logada = $this->getSession()->id_pessoa ?? null; + } + + /** + * @see CoreExt_Configurable::setOptions($options) + */ + public function setOptions(array $options = []) + { + $options = array_change_key_case($options, CASE_LOWER); + + if (isset($options['datamapper'])) { + $this->setDataMapper($options['datamapper']); + unset($options['datamapper']); + } + + if (isset($options['processoap'])) { + $this->setBaseProcessoAp($options['processoap']); + unset($options['processoap']); + } + + if (isset($options['titulo'])) { + $this->setBaseTitulo($options['titulo']); + unset($options['titulo']); + } + + $defaultOptions = array_keys($this->getOptions()); + $passedOptions = array_keys($options); + + if (0 < count(array_diff($passedOptions, $defaultOptions))) { + throw new CoreExt_Exception_InvalidArgumentException( + sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) + ); + } + + $this->_options = array_merge($this->getOptions(), $options); + + return $this; + } + + /** + * @see CoreExt_Configurable::getOptions() + */ + public function getOptions() + { + return $this->_options; + } + + /** + * Setter. + * + * @param CoreExt_Controller|string $dataMapper + * + * @return Core_Controller_Page_Interface Provê interface fluída + * + * @throws Core_Controller_Page_Exception|CoreExt_Exception_InvalidArgumentException + */ + public function setDataMapper($dataMapper) + { + if (is_string($dataMapper)) { + if (class_exists($dataMapper)) { + $this->_dataMapper = new $dataMapper(); + } else { + throw new Core_Controller_Page_Exception('A classe "' . $dataMapper . '" não existe.'); + } + } elseif ($dataMapper instanceof CoreExt_DataMapper) { + $this->_dataMapper = $dataMapper; + } else { + throw new CoreExt_Exception_InvalidArgumentException('Argumento inválido. São aceitos apenas argumentos do tipo string e CoreExt_DataMapper'); + } + + return $this; + } + + /** + * Getter. + * + * Facilita a subclassificação ao permitir herança tanto via configuração do + * atributo $_dataMapper ou da sobrescrição de setDataMapper(). + * + * @see Core_Controller_Page_Interface::getDataMapper() + */ + public function getDataMapper() + { + if (is_string($this->_dataMapper)) { + $this->setDataMapper($this->_dataMapper); + } elseif (is_null($this->_dataMapper)) { + throw new Core_Controller_Page_Exception('É necessário especificar um nome de classe para a propriedade "$_dataMapper" ou sobrescrever o método "getDataMapper()".'); + } + + return $this->_dataMapper; + } + + /** + * Setter. + * + * @param CoreExt_Entity $entity + * + * @return Core_Controller_Page_Abstract Provê interface fluída + */ + public function setEntity(CoreExt_Entity $entity) + { + $this->_entity = $entity; + + return $this; } - if (isset($options['processoap'])) { - $this->setBaseProcessoAp($options['processoap']); - unset($options['processoap']); + /** + * Getter. + * + * Se nenhuma instância CoreExt_Entity existir, tenta instanciar uma através + * de CoreExt_DataMapper. + * + * @return CoreExt_Entity|NULL + * + * @throws Core_Controller_Page_Exception + */ + public function getEntity() + { + if (is_null($this->_entity)) { + $this->setEntity($this->getDataMapper()->createNewEntityInstance()); + } + + return $this->_entity; } - if (isset($options['titulo'])) { - $this->setBaseTitulo($options['titulo']); - unset($options['titulo']); + /** + * @see CoreExt_Entity::hasError($key) + */ + public function hasError($key) + { + return $this->getEntity()->hasError($key); } - $defaultOptions = array_keys($this->getOptions()); - $passedOptions = array_keys($options); + /** + * @see CoreExt_Entity::hasErrors() + */ + public function hasErrors() + { + return $this->getEntity()->hasErrors(); + } - if (0 < count(array_diff($passedOptions, $defaultOptions))) { - throw new CoreExt_Exception_InvalidArgumentException( - sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) - ); + /** + * @see CoreExt_Entity::getError($key) + */ + public function getError($key) + { + return $this->getEntity()->getError($key); } - $this->_options = array_merge($this->getOptions(), $options); - return $this; - } - - /** - * @see CoreExt_Configurable#getOptions() - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Setter. - * @param CoreExt_Controller|string $dataMapper - * @return Core_Controller_Page_Interface Provê interface fluída - * @throws Core_Controller_Page_Exception|CoreExt_Exception_InvalidArgumentException - */ - public function setDataMapper($dataMapper) - { - if (is_string($dataMapper)) { - if (class_exists($dataMapper)) { - $this->_dataMapper = new $dataMapper(); - } - else { - throw new Core_Controller_Page_Exception('A classe "'. $dataMapper .'" não existe.'); - } + /** + * @see CoreExt_Entity::getErrors() + */ + public function getErrors() + { + return $this->getEntity()->getErrors(); } - elseif ($dataMapper instanceof CoreExt_DataMapper) { - $this->_dataMapper = $dataMapper; + + /** + * Setter. + * + * @param int $processoAp + * + * @return Core_Controller_Page_Abstract + */ + public function setBaseProcessoAp($processoAp) + { + $this->_processoAp = (int) $processoAp; + + return $this; } - else { - throw new CoreExt_Exception_InvalidArgumentException('Argumento inválido. São aceitos apenas argumentos do tipo string e CoreExt_DataMapper'); + + /** + * Getter. + * + * Facilita a subclassificação ao permitir herança tanto via configuração do + * atributo $_processoAp ou da sobrescrição de setBaseProcessoAp(). + * + * @see Core_Controller_Page_Interface::getBaseProcessoAp() + * + * @return int + * + * @throws Core_Controller_Page_Exception + */ + public function getBaseProcessoAp() + { + if (is_null($this->_processoAp)) { + throw new Core_Controller_Page_Exception('É necessário especificar um valor numérico para a propriedade "$_processoAp" ou sobrescrever o método "getBaseProcessoAp()".'); + } + + return $this->_processoAp; } - return $this; - } - - /** - * Getter. - * - * Facilita a subclassificação ao permitir herança tanto via configuração do - * atributo $_dataMapper ou da sobrescrição de setDataMapper(). - * - * @see Core_Controller_Page_Interface#getDataMapper() - */ - public function getDataMapper() - { - if (is_string($this->_dataMapper)) { - $this->setDataMapper($this->_dataMapper); + + /** + * Setter. + * + * @see Core_Controller_Page_Interface::setBaseTitulo($titulo) + */ + public function setBaseTitulo($titulo) + { + $this->_titulo = (string) $titulo; + + return $this; } - elseif (is_null($this->_dataMapper)) { - throw new Core_Controller_Page_Exception('É necessário especificar um nome de classe para a propriedade "$_dataMapper" ou sobrescrever o método "getDataMapper()".'); + + /** + * Getter. + * + * Facilita a subclassificação ao permitir herança tanto via configuração do + * atributo $_titulo ou da sobrescrição de setBaseTitulo(). + * + * @see Core_Controller_Page_Interface::getBaseTitulo() + * + * @return string + * + * @throws Core_Controller_Page_Exception + */ + public function getBaseTitulo() + { + if (is_null($this->_titulo)) { + throw new Core_Controller_Page_Exception('É necessário especificar uma string para a propriedade "$_titulo" ou sobrescrever o método "getBaseTitulo()".'); + } + + return $this->_titulo; } - return $this->_dataMapper; - } - - /** - * Setter. - * @param CoreExt_Entity $entity - * @return CoreExt_Controller_Page_Abstract Provê interface fluída - */ - public function setEntity(CoreExt_Entity $entity) - { - $this->_entity = $entity; - return $this; - } - - /** - * Getter. - * - * Se nenhuma instância CoreExt_Entity existir, tenta instanciar uma através - * de CoreExt_DataMapper. - * - * @return CoreExt_Entity|NULL - */ - public function getEntity() - { - if (is_null($this->_entity)) { - $this->setEntity($this->getDataMapper()->createNewEntityInstance()); + + /** + * Adiciona uma entrada nos arrays de botões (renderizado por RenderHTML(), + * nas classes cls(Cadastro|Detalhe|Listagem)). + * + * @param string $label + * @param string $url + * + * @return Core_Controller_Page_Abstract Provê interface fluída + */ + public function addBotao($label, $url) + { + $this->array_botao[] = $label; + $this->array_botao_url[] = $url; + + return $this; } - return $this->_entity; - } - - /** - * @see CoreExt_Entity#hasError($key) - */ - public function hasError($key) - { - return $this->getEntity()->hasError($key); - } - - /** - * @see CoreExt_Entity#hasErrors() - */ - public function hasErrors() - { - return $this->getEntity()->hasErrors(); - } - - /** - * @see CoreExt_Entity#getError($key) - */ - public function getError($key) - { - return $this->getEntity()->getError($key); - } - - /** - * @see CoreExt_Entity#getErrors() - */ - public function getErrors() - { - return $this->getEntity()->getErrors(); - } - - /** - * Setter. - * @param int $processoAp - * @return Core_Controller_Page_Abstract - */ - public function setBaseProcessoAp($processoAp) - { - $this->_processoAp = (int) $processoAp; - return $this; - } - - /** - * Getter. - * - * Facilita a subclassificação ao permitir herança tanto via configuração do - * atributo $_processoAp ou da sobrescrição de setBaseProcessoAp(). - * - * @return int - * @see Core_Controller_Page_Interface#getBaseProcessoAp() - */ - public function getBaseProcessoAp() - { - if (is_null($this->_processoAp)) { - throw new Core_Controller_Page_Exception('É necessário especificar um valor numérico para a propriedade "$_processoAp" ou sobrescrever o método "getBaseProcessoAp()".'); + + /** + * Configura botões padrão de clsCadastro + * + * @return Core_Controller_Page_Abstract Provê interface fluída + */ + public function configurarBotoes() + { + // Botão Cancelar (clsDetalhe e clsCadastro) + if ($this->_hasOption('url_cancelar')) { + $config = $this->getOption('url_cancelar'); + + if (is_string($config)) { + $this->url_cancelar = $config; + } elseif (is_array($config)) { + $this->url_cancelar = CoreExt_View_Helper_UrlHelper::url( + $config['path'], + $config['options'] + ); + } + } + + return $this; } - return $this->_processoAp; - } - - /** - * Setter. - * @see Core_Controller_Page_Interface#setBaseTitulo($titulo) - */ - public function setBaseTitulo($titulo) - { - $this->_titulo = (string) $titulo; - return $this; - } - - /** - * Getter. - * - * Facilita a subclassificação ao permitir herança tanto via configuração do - * atributo $_titulo ou da sobrescrição de setBaseTitulo(). - * - * @return string - * @see Core_Controller_Page_Interface#getBaseTitulo() - */ - public function getBaseTitulo() - { - if (is_null($this->_titulo)) { - throw new Core_Controller_Page_Exception('É necessário especificar uma string para a propriedade "$_titulo" ou sobrescrever o método "getBaseTitulo()".'); + + /** + * Hook de pré-execução do método RenderHTML(). + * + * @return Core_Controller_Page_Abstract Provê interface fluída + */ + protected function _preRender() + { + return $this->configurarBotoes(); } - return $this->_titulo; - } - - /** - * Adiciona uma entrada nos arrays de botões (renderizado por RenderHTML(), - * nas classes cls(Cadastro|Detalhe|Listagem)). - * - * @param string $label - * @param string $url - * @return Core_Controller_Page_Abstract Provê interface fluída - */ - public function addBotao($label, $url) - { - $this->array_botao[] = $label; - $this->array_botao_url[] = $url; - return $this; - } - - /** - * Configura botões padrão de clsCadastro - * @return Core_Controller_Page_Abstract Provê interface fluída - */ - public function configurarBotoes() - { - // Botão Cancelar (clsDetalhe e clsCadastro) - if ($this->_hasOption('url_cancelar')) { - $config = $this->getOption('url_cancelar'); - if (is_string($config)) { - $this->url_cancelar = $config; - } - elseif (is_array($config)) { - $this->url_cancelar = CoreExt_View_Helper_UrlHelper::url( - $config['path'], $config['options'] - ); - } + + /** + * Adiciona conteúdo HTML após o conteúdo gerado por um + * Core_Controller_Page_Abstract. + * + * @param string $data A string HTML a ser adiciona após o conteúdo. + * + * @return Core_Controller_Page_Abstract Provê interface fluída + */ + public function appendOutput($data) + { + if (!empty($data) && is_string($data)) { + $this->_output['append'][] = $data; + } + + return $this; + } + + /** + * Retorna todo o conteúdo acrescentado como uma string. + * + * @return string O conteúdo a ser acrescentado separado com uma quebra de linha. + * + * @see clsBase::MakeBody() + */ + public function getAppendedOutput() + { + return $this->_getOutput('append'); } - return $this; - } - - /** - * Hook de pré-execução do método RenderHTML(). - * @return Core_Controller_Page_Abstract Provê interface fluída - */ - protected function _preRender() - { - return $this->configurarBotoes(); - } - - /** - * Adiciona conteúdo HTML após o conteúdo gerado por um - * Core_Controller_Page_Abstract. - * - * @param string $data A string HTML a ser adiciona após o conteúdo. - * @return Core_Controller_Page_Abstract Provê interface fluída - */ - public function appendOutput($data) - { - if (!empty($data) && is_string($data)) { - $this->_output['append'][] = $data; + + /** + * Adiciona conteúdo HTML antes do conteúdo HTML gerado por um + * Core_Controller_Page_Abstract. + * + * @param string $data A string HTML a ser adiciona após o conteúdo. + * + * @return Core_Controller_Page_Abstract Provê interface fluída + */ + public function prependOutput($data) + { + if (!empty($data) && is_string($data)) { + $this->_output['prepend'][] = $data; + } + + return $this; } - return $this; - } - - /** - * Retorna todo o conteúdo acrescentado como uma string. - * @return string O conteúdo a ser acrescentado separado com uma quebra de linha. - * @see clsBase#MakeBody() - */ - public function getAppendedOutput() - { - return $this->_getOutput('append'); - } - - /** - * Adiciona conteúdo HTML antes do conteúdo HTML gerado por um - * Core_Controller_Page_Abstract. - * - * @param string $data A string HTML a ser adiciona após o conteúdo. - * @return Core_Controller_Page_Abstract Provê interface fluída - */ - public function prependOutput($data) - { - if (!empty($data) && is_string($data)) { - $this->_output['prepend'][] = $data; + + /** + * Retorna todo o conteúdo prefixado como uma string. + * + * @return string O conteúdo a ser prefixado separado com uma quebra de linha. + * + * @see clsBase::MakeBody() + */ + public function getPrependedOutput() + { + return $this->_getOutput('prepend'); } - return $this; - } - - /** - * Retorna todo o conteúdo prefixado como uma string. - * @return string O conteúdo a ser prefixado separado com uma quebra de linha. - * @see clsBase#MakeBody() - */ - public function getPrependedOutput() - { - return $this->_getOutput('prepend'); - } - - /** - * Retorna o conteúdo a ser adicionado a saída de acordo com a região. - * @param string $pos Região para retornar o conteúdo a ser adicionado na saída. - * @return string|NULL Conteúdo da região separado por uma quebra de linha ou - * NULL caso a região não exista. - */ - private function _getOutput($pos = 'prepend') - { - if (isset($this->_output[$pos])) { - return implode(PHP_EOL, $this->_output[$pos]); + + /** + * Retorna o conteúdo a ser adicionado a saída de acordo com a região. + * + * @param string $pos Região para retornar o conteúdo a ser adicionado na saída. + * + * @return string|NULL Conteúdo da região separado por uma quebra de linha ou + * NULL caso a região não exista. + */ + private function _getOutput($pos = 'prepend') + { + if (isset($this->_output[$pos])) { + return implode(PHP_EOL, $this->_output[$pos]); + } + + return null; } - return NULL; - } - - /** - * @see CoreExt_Controller_Interface#dispatch() - */ - public function dispatch() - { - return $this; - } - - /** - * @see Core_Controller_Page_Interface#generate($instance) - */ - public function generate(CoreExt_Controller_Page_Interface $instance) - { - require_once 'Core/View.php'; - Core_View::generate($instance); - } - - public function getQueryString($name, $default = null) - { - if (!isset($_GET[$name])) { - return $default; + + /** + * @see CoreExt_Controller_Interface::dispatch() + */ + public function dispatch() + { + return $this; } - switch ($_GET[$name]) { - case '': - case null: - $value = $default; - break; - default: - $value = $_GET[$name]; + /** + * @see Core_Controller_Page_Interface::generate($instance) + */ + public function generate(CoreExt_Controller_Page_Interface $instance) + { + require_once 'Core/View.php'; + Core_View::generate($instance); } - return $value; - } + public function getQueryString($name, $default = null) + { + if (!isset($_GET[$name])) { + return $default; + } - public function breadcrumb($currentPage, $breadcrumbs = []) - { - $breadcrumb = new Breadcrumb(); - $breadcrumb = $breadcrumb->makeBreadcrumb($currentPage, $breadcrumbs); - $this->locale = $breadcrumb; - } + switch ($_GET[$name]) { + case '': + case null: + $value = $default; + break; + + default: + $value = $_GET[$name]; + } + + return $value; + } + + public function breadcrumb($currentPage, $breadcrumbs = []) + { + $breadcrumb = new Breadcrumb(); + $breadcrumb = $breadcrumb->makeBreadcrumb($currentPage, $breadcrumbs); + $this->locale = $breadcrumb; + } } diff --git a/ieducar/lib/Core/Controller/Page/EditController.php b/ieducar/lib/Core/Controller/Page/EditController.php index 804ac15f8d..a0311fe200 100644 --- a/ieducar/lib/Core/Controller/Page/EditController.php +++ b/ieducar/lib/Core/Controller/Page/EditController.php @@ -1,424 +1,416 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'include/clsCadastro.inc.php'; require_once 'Core/Controller/Page/Validatable.php'; require_once 'App/Model/NivelAcesso.php'; require_once 'App/Model/NivelTipoUsuario.php'; -/** - * Core_Controller_Page_EditController abstract class. - * - * Provê um page controller padrão para páginas de edição e criação de registros. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Classe disponível desde a versão 1.1.0 - * @todo Documentar a API - * @todo Definir o atributo $_formMap que é diferente do atributo - * semelhante dos outros controllers (view|list) - * @todo Documentar as opções new_success e edit_success - * @version @@package_version@@ - */ -abstract class Core_Controller_Page_EditController - extends clsCadastro - implements Core_Controller_Page_Validatable +abstract class Core_Controller_Page_EditController extends clsCadastro implements Core_Controller_Page_Validatable { - /** - * Array associativo de um elemento de formulário, usado para a definição - * de labels, nome de campos e definição de qual campo foi invalidado por - * CoreExt_DataMapper::isValid(). - * - * @var array - */ - protected $_formMap = array(); - - /** - * Determina se "Cadastrar" ou "Atualizar" são ações disponíveis na interface. - * @var bool - */ - protected $_saveOption = FALSE; - - /** - * Determina se "Excluir" é uma ação disponível na interface. - * @var bool - */ - protected $_deleteOption = FALSE; - - /** - * Determina o nível de acesso necessário para as ações de Cadastro/Exclusão. - * @var int - */ - protected $_nivelAcessoOption = App_Model_NivelAcesso::INSTITUCIONAL; - - /** - * Determina um caminho para redirecionar o usuário caso seus privilégios de - * acesso sejam insuficientes. - * @var string - */ - protected $_nivelAcessoInsuficiente = NULL; - - /** - * @var clsPermissoes - */ - protected $_clsPermissoes = NULL; - - /** - * Chama o construtor da superclasse para atribuir $tipoacao do $_POST. - */ - public function __construct() - { - $this->setDataMapper($this->getDataMapper()); - - // Adiciona novos itens de configuração - $this->_options = $this->_options + array( - 'save_action' => $this->_saveOption, - 'delete_action' => $this->_deleteOption, - 'nivel_acesso' => $this->_nivelAcessoOption, - 'nivel_acesso_insuficiente' => $this->_nivelAcessoInsuficiente - ); - - // Configura botões padrão - if (0 < $this->getRequest()->id) { - $this->setOptions(array( - 'url_cancelar' => array( - 'path' => 'view', - 'options' => array('query' => array('id' => $this->getRequest()->id)) - ) - )); + /** + * Array associativo de um elemento de formulário, usado para a definição + * de labels, nome de campos e definição de qual campo foi invalidado por + * CoreExt_DataMapper::isValid(). + * + * @var array + */ + protected $_formMap = []; + + /** + * Determina se "Cadastrar" ou "Atualizar" são ações disponíveis na interface. + * + * @var bool + */ + protected $_saveOption = false; + + /** + * Determina se "Excluir" é uma ação disponível na interface. + * + * @var bool + */ + protected $_deleteOption = false; + + /** + * Determina o nível de acesso necessário para as ações de Cadastro/Exclusão. + * + * @var int + */ + protected $_nivelAcessoOption = App_Model_NivelAcesso::INSTITUCIONAL; + + /** + * Determina um caminho para redirecionar o usuário caso seus privilégios de + * acesso sejam insuficientes. + * + * @var string + */ + protected $_nivelAcessoInsuficiente = null; + + /** + * @var clsPermissoes + */ + protected $_clsPermissoes = null; + + /** + * Chama o construtor da superclasse para atribuir $tipoacao do $_POST. + */ + public function __construct() + { + $this->setDataMapper($this->getDataMapper()); + + // Adiciona novos itens de configuração + $this->_options = $this->_options + [ + 'save_action' => $this->_saveOption, + 'delete_action' => $this->_deleteOption, + 'nivel_acesso' => $this->_nivelAcessoOption, + 'nivel_acesso_insuficiente' => $this->_nivelAcessoInsuficiente + ]; + + // Configura botões padrão + if (0 < $this->getRequest()->id) { + $this->setOptions([ + 'url_cancelar' => [ + 'path' => 'view', + 'options' => ['query' => ['id' => $this->getRequest()->id]] + ] + ]); + } + + $this->_preConstruct(); + parent::__construct(); + $this->_postConstruct(); } - $this->_preConstruct(); - parent::__construct(); - $this->_postConstruct(); - } - - /** - * Subclasses podem sobrescrever esse método para executar operações antes - * da chamada ao construtor de clsCadastro(). - */ - protected function _preConstruct() - { - } - - /** - * Subclasses podem sobrescrever esse método para executar operações após - * a chamada ao construtor de clsCadastro(). - */ - protected function _postConstruct() - { - } - - /** - * Retorna um label de um item de formulário. - * @param string $key - * @return string - */ - protected function _getLabel($key) - { - return $this->_formMap[$key]['label']; - } - - /** - * Retorna uma string de ajuda para um item de formulário. - * @param string $key - * @return string - */ - protected function _getHelp($key) - { - return $this->_formMap[$key]['help']; - } - - /** - * Retorna o atributo de CoreExt_Entity para recuperar o valor de um item - * de formulário. - * @param string $key - * @return mixed - */ - protected function _getEntity($key) - { - return $this->_formMap[$key]['entity']; - } - - /** - * Retorna um label de um item de formulário através do nome de um atributo de - * CoreExt_Entity. - * @param string $key - * @return string - */ - protected function _getEntityLabel($key) - { - foreach ($this->_formMap as $oKey => $map) { - if ($key == $map['entity'] || $key == $oKey) { - return $map['label']; - } + /** + * Subclasses podem sobrescrever esse método para executar operações antes + * da chamada ao construtor de clsCadastro(). + */ + protected function _preConstruct() + { } - } - - /** - * @see Core_Controller_Page_Validatable#getValidators() - */ - public function getValidators() - { - return array(); - } - - /** - * Sobrescreve o método Inicializar() de clsCadastro com operações padrões - * para o caso de uma CoreExt_Entity que use o campo identidade id. - * - * Seu comportamento pode ser alterado sobrescrevendo-se os métodos _initNovo - * e _initEditar. - * - * O retorno desse método é usado em RenderHTML() que define qual método de - * sua API (Novo, Editar, Excluir ou Gerar) será chamado. - * - * @return string - * @see clsCadastro#RenderHTML() - * @see clsCadastro#Inicializar() - * @todo Controle de permissão - */ - public function Inicializar() - { - if ($this->_initNovo()) { - return "Novo"; + + /** + * Subclasses podem sobrescrever esse método para executar operações após + * a chamada ao construtor de clsCadastro(). + */ + protected function _postConstruct() + { } - if ($this->getOption('save_action')) { - $this->_hasPermissaoCadastra(); + /** + * Retorna um label de um item de formulário. + * + * @param string $key + * + * @return string + */ + protected function _getLabel($key) + { + return $this->_formMap[$key]['label']; } - // Habilita botão de exclusão de registro - if ($this->getOption('delete_action')) { - $this->fexcluir = $this->_hasPermissaoExcluir(); + /** + * Retorna uma string de ajuda para um item de formulário. + * + * @param string $key + * + * @return string + */ + protected function _getHelp($key) + { + return $this->_formMap[$key]['help']; } - if ($this->_initEditar()) { - return "Editar"; + /** + * Retorna o atributo de CoreExt_Entity para recuperar o valor de um item + * de formulário. + * + * @param string $key + * + * @return mixed + */ + protected function _getEntity($key) + { + return $this->_formMap[$key]['entity']; } - } - - /** - * Verifica se o usuário possui privilégios de cadastro para o processo. - * @return bool|void Redireciona caso a opção 'nivel_acesso_insuficiente' seja - * diferente de NULL. - */ - protected function _hasPermissaoCadastra() - { - return $this->getClsPermissoes()->permissao_cadastra( - $this->getBaseProcessoAp(), - $this->getOption('id_usuario'), - $this->getOption('nivel_acesso'), - $this->getOption('nivel_acesso_insuficiente') - ); - } - - /** - * Verifica se o usuário possui privilégios de cadastro para o processo. - * @return bool - */ - protected function _hasPermissaoExcluir() - { - return $this->getClsPermissoes()->permissao_excluir( - $this->getBaseProcessoAp(), - $this->getOption('id_usuario'), - $this->getOption('nivel_acesso') - ); - } - - /** - * Setter. - * @param clsPemissoes $instance - * @return CoreExt_Controller_Page_Abstract Provê interface fluída - */ - public function setClsPermissoes(clsPermissoes $instance) - { - $this->_clsPermissoes = $instance; - return $this; - } - - /** - * Getter. - * @return clsPermissoes - */ - public function getClsPermissoes() - { - if (is_null($this->_clsPermissoes)) { - require_once 'include/pmieducar/clsPermissoes.inc.php'; - $this->setClsPermissoes(new clsPermissoes()); + + /** + * Retorna um label de um item de formulário através do nome de um atributo de + * CoreExt_Entity. + * + * @param string $key + * + * @return string + */ + protected function _getEntityLabel($key) + { + foreach ($this->_formMap as $oKey => $map) { + if ($key == $map['entity'] || $key == $oKey) { + return $map['label']; + } + } } - return $this->_clsPermissoes; - } - - /** - * Hook de execução para verificar se CoreExt_Entity é novo. Verifica - * simplesmente se o campo identidade foi passado na requisição HTTP e, se não - * for, cria uma instância de CoreExt_Entity vazia. - * - * @return bool - */ - protected function _initNovo() - { - if (!isset($this->getRequest()->id)) { - $this->setEntity($this->getDataMapper()->createNewEntityInstance()); - return TRUE; + + /** + * @see Core_Controller_Page_Validatable::getValidators() + */ + public function getValidators() + { + return []; } - return FALSE; - } - - /** - * Hook de execução para verificar se CoreExt_Entity é existente através do - * campo identidade passado pela requisição HTTP. - * - * @return bool - */ - protected function _initEditar() - { - try { - $this->setEntity($this->getDataMapper()->find($this->getRequest()->id)); - } catch(Exception $e) { - $this->mensagem = $e; - return FALSE; + + /** + * Sobrescreve o método Inicializar() de clsCadastro com operações padrões + * para o caso de uma CoreExt_Entity que use o campo identidade id. + * + * Seu comportamento pode ser alterado sobrescrevendo-se os métodos _initNovo + * e _initEditar. + * + * O retorno desse método é usado em RenderHTML() que define qual método de + * sua API (Novo, Editar, Excluir ou Gerar) será chamado. + * + * @return string + * + * @see clsCadastro::RenderHTML() + * @see clsCadastro::Inicializar() + * + * @throws Core_Controller_Page_Exception + */ + public function Inicializar() + { + if ($this->_initNovo()) { + return 'Novo'; + } + + if ($this->getOption('save_action')) { + $this->_hasPermissaoCadastra(); + } + + // Habilita botão de exclusão de registro + if ($this->getOption('delete_action')) { + $this->fexcluir = $this->_hasPermissaoExcluir(); + } + + if ($this->_initEditar()) { + return 'Editar'; + } } - return TRUE; - } - - /** - * Insere um novo registro no banco de dados e redireciona para a página - * definida pela opção "new_success". - * @see clsCadastro#Novo() - */ - public function Novo() - { - if ($this->_save()) { - $params = ''; - if (0 < count($this->getOption('new_success_params')) && - is_array($this->getOption('new_success_params'))) { - $params = '?' . http_build_query($this->getOption('new_success_params')); - } - - $this->redirect($this->getDispatcher()->getControllerName() . '/' . - $this->getOption('new_success') . $params); + + /** + * Verifica se o usuário possui privilégios de cadastro para o processo. + * + * @return bool|void Redireciona caso a opção 'nivel_acesso_insuficiente' seja diferente de NULL. + * + * @throws Core_Controller_Page_Exception + */ + protected function _hasPermissaoCadastra() + { + return $this->getClsPermissoes()->permissao_cadastra( + $this->getBaseProcessoAp(), + $this->getOption('id_usuario'), + $this->getOption('nivel_acesso'), + $this->getOption('nivel_acesso_insuficiente') + ); } - return FALSE; - } - - /** - * Atualiza um registro no banco de dados e redireciona para a página - * definida pela opção "edit_success". - * - * Possibilita o uso de uma query string padronizada, usando o array - * armazenado na opção "edit_success_params" - * - * @see clsCadastro#Editar() - */ - public function Editar() - { - if ($this->_save()) { - if (0 < count($this->getOption('edit_success_params')) && - is_array($this->getOption('edit_success_params'))) { - $params = http_build_query($this->getOption('edit_success_params')); - } - else { - $params = 'id=' . floatval($this->getEntity()->id); - } - $this->redirect($this->getDispatcher()->getControllerName() . '/' - . $this->getOption('edit_success') - . '?' . $params); + + /** + * Verifica se o usuário possui privilégios de cadastro para o processo. + * + * @return bool + * + * @throws Core_Controller_Page_Exception + */ + protected function _hasPermissaoExcluir() + { + return $this->getClsPermissoes()->permissao_excluir( + $this->getBaseProcessoAp(), + $this->getOption('id_usuario'), + $this->getOption('nivel_acesso') + ); + } + + /** + * Setter. + * + * @param clsPermissoes $instance + * + * @return Core_Controller_Page_EditController + */ + public function setClsPermissoes(clsPermissoes $instance) + { + $this->_clsPermissoes = $instance; + + return $this; } - return FALSE; - } - - /** - * Apaga um registro no banco de dados e redireciona para a página indicada - * pela opção "delete_success". - * @see clsCadastro#Excluir() - */ - function Excluir() - { - if (isset($this->getRequest()->id)) { - if ($this->getDataMapper()->delete($this->getRequest()->id)) { - if (is_array($this->getOption('delete_success_params'))) { - $params = http_build_query($this->getOption('delete_success_params')); + + /** + * Getter. + * + * @return clsPermissoes + */ + public function getClsPermissoes() + { + if (is_null($this->_clsPermissoes)) { + require_once 'include/pmieducar/clsPermissoes.inc.php'; + $this->setClsPermissoes(new clsPermissoes()); } - $this->redirect( - $this->getDispatcher()->getControllerName() . '/' . - $this->getOption('delete_success') . - (isset($params) ? '?' . $params : '') - ); - } + return $this->_clsPermissoes; } - return FALSE; - } - - /** - * Implementa uma rotina de criação ou atualização de registro padrão para - * uma instância de CoreExt_Entity que use um campo identidade. - * @return bool - * @todo Atualizar todas as Exception de CoreExt_Validate, para poder ter - * certeza que o erro ocorrido foi gerado de alguma camada diferente, como - * a de conexão com o banco de dados. - */ - protected function _save() - { - $data = array(); - - foreach ($_POST as $key => $val) { - if (array_key_exists($key, $this->_formMap)) { - $data[$key] = $val; - } + + /** + * Hook de execução para verificar se CoreExt_Entity é novo. Verifica + * simplesmente se o campo identidade foi passado na requisição HTTP e, se não + * for, cria uma instância de CoreExt_Entity vazia. + * + * @return bool + * + * @throws Core_Controller_Page_Exception + */ + protected function _initNovo() + { + if (!isset($this->getRequest()->id)) { + $this->setEntity($this->getDataMapper()->createNewEntityInstance()); + + return true; + } + + return false; } - // Verifica pela existência do field identity - if (isset($this->getRequest()->id) && 0 < $this->getRequest()->id) { - $entity = $this->setEntity($this->getDataMapper()->find($this->getRequest()->id)); + /** + * Hook de execução para verificar se CoreExt_Entity é existente através do + * campo identidade passado pela requisição HTTP. + * + * @return bool + */ + protected function _initEditar() + { + try { + $this->setEntity($this->getDataMapper()->find($this->getRequest()->id)); + } catch (Exception $e) { + $this->mensagem = $e; + + return false; + } + + return true; } - if (isset($entity)) { - $this->getEntity()->setOptions($data); + /** + * Insere um novo registro no banco de dados e redireciona para a página + * definida pela opção "new_success". + * + * @see clsCadastro::Novo() + */ + public function Novo() + { + if ($this->_save()) { + $params = ''; + + if (0 < count($this->getOption('new_success_params')) && + is_array($this->getOption('new_success_params'))) { + $params = '?' . http_build_query($this->getOption('new_success_params')); + } + + $this->redirect( + $this->getDispatcher()->getControllerName() . '/' . $this->getOption('new_success') . $params + ); + } + + return false; } - else { - $this->setEntity($this->getDataMapper()->createNewEntityInstance($data)); + + /** + * Atualiza um registro no banco de dados e redireciona para a página + * definida pela opção "edit_success". + * + * Possibilita o uso de uma query string padronizada, usando o array + * armazenado na opção "edit_success_params" + * + * @see clsCadastro::Editar() + */ + public function Editar() + { + if ($this->_save()) { + if (0 < count($this->getOption('edit_success_params')) && + is_array($this->getOption('edit_success_params'))) { + $params = http_build_query($this->getOption('edit_success_params')); + } else { + $params = 'id=' . floatval($this->getEntity()->id); + } + + $this->redirect( + $this->getDispatcher()->getControllerName() . '/' + . $this->getOption('edit_success') + . '?' . $params + ); + } + + return false; } - try { - $this->getDataMapper()->save($this->getEntity()); - return TRUE; + /** + * Apaga um registro no banco de dados e redireciona para a página indicada + * pela opção "delete_success". + * + * @see clsCadastro::Excluir() + */ + public function Excluir() + { + if (isset($this->getRequest()->id)) { + if ($this->getDataMapper()->delete($this->getRequest()->id)) { + if (is_array($this->getOption('delete_success_params'))) { + $params = http_build_query($this->getOption('delete_success_params')); + } + + $this->redirect( + $this->getDispatcher()->getControllerName() . '/' . + $this->getOption('delete_success') . + (isset($params) ? '?' . $params : '') + ); + } + } + + return false; } - catch (Exception $e) { - // TODO: ver @todo do docblock - $this->mensagem = 'Erro no preenchimento do formulário. '; - return FALSE; + + /** + * Implementa uma rotina de criação ou atualização de registro padrão para + * uma instância de CoreExt_Entity que use um campo identidade. + * + * @return bool + * + * @throws Core_Controller_Page_Exception + */ + protected function _save() + { + $data = []; + + foreach ($_POST as $key => $val) { + if (array_key_exists($key, $this->_formMap)) { + $data[$key] = $val; + } + } + + // Verifica pela existência do field identity + if (isset($this->getRequest()->id) && 0 < $this->getRequest()->id) { + $entity = $this->setEntity($this->getDataMapper()->find($this->getRequest()->id)); + } + + if (isset($entity)) { + $this->getEntity()->setOptions($data); + } else { + $this->setEntity($this->getDataMapper()->createNewEntityInstance($data)); + } + + try { + $this->getDataMapper()->save($this->getEntity()); + + return true; + } catch (Exception $e) { + $this->mensagem = 'Erro no preenchimento do formulário. '; + + return false; + } } - } } diff --git a/ieducar/lib/Core/Controller/Page/Exception.php b/ieducar/lib/Core/Controller/Page/Exception.php index 5d88584191..e1c4d5e891 100644 --- a/ieducar/lib/Core/Controller/Page/Exception.php +++ b/ieducar/lib/Core/Controller/Page/Exception.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Exception.php'; -/** - * Core_Controller_Page_Exception class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class Core_Controller_Page_Exception extends CoreExt_Exception { } diff --git a/ieducar/lib/Core/Controller/Page/Interface.php b/ieducar/lib/Core/Controller/Page/Interface.php index 5db746637c..1b821a9608 100644 --- a/ieducar/lib/Core/Controller/Page/Interface.php +++ b/ieducar/lib/Core/Controller/Page/Interface.php @@ -1,82 +1,54 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Controller/Page/Interface.php'; -/** - * Core_Controller_Page_Interface interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface Core_Controller_Page_Interface extends CoreExt_Controller_Page_Interface { - /** - * Setter. - * @param CoreExt_DataMapper|string - * @return Core_Controller_Page_Interface Provê interface fluída - */ - public function setDataMapper($dataMapper); - - /** - * Retorna uma instância CoreExt_DataMapper. - * @return CoreExt_DataMapper - */ - public function getDataMapper(); - - /** - * Setter. - * @return Core_Controller_Page_Interface Provê interface fluída - */ - public function setBaseTitulo($titulo); - - /** - * Retorna uma string para o título da página. - * @return string - */ - public function getBaseTitulo(); - - /** - * Setter. - * @param int $processoAp - * @return Core_Controller_Page_Interface Provê interface fluída - */ - public function setBaseProcessoAp($processoAp); - - /** - * Retorna o código de processo para autorização de acesso ao usuário. - * @return int - */ - public function getBaseProcessoAp(); + /** + * Setter. + * + * @param CoreExt_DataMapper|string $dataMapper + * + * @return Core_Controller_Page_Interface Provê interface fluída + */ + public function setDataMapper($dataMapper); + + /** + * Retorna uma instância CoreExt_DataMapper. + * + * @return CoreExt_DataMapper + */ + public function getDataMapper(); + + /** + * Setter. + * + * @param string $titulo + * + * @return Core_Controller_Page_Interface Provê interface fluída + */ + public function setBaseTitulo($titulo); + + /** + * Retorna uma string para o título da página. + * + * @return string + */ + public function getBaseTitulo(); + + /** + * Setter. + * + * @param int $processoAp + * + * @return Core_Controller_Page_Interface Provê interface fluída + */ + public function setBaseProcessoAp($processoAp); + + /** + * Retorna o código de processo para autorização de acesso ao usuário. + * + * @return int + */ + public function getBaseProcessoAp(); } diff --git a/ieducar/lib/Core/Controller/Page/ListController.php b/ieducar/lib/Core/Controller/Page/ListController.php index f5294a9d0c..dc4593d30a 100644 --- a/ieducar/lib/Core/Controller/Page/ListController.php +++ b/ieducar/lib/Core/Controller/Page/ListController.php @@ -1,166 +1,132 @@ - * - * Este programa י software livre; vocך pode redistribuם-lo e/ou modificב-lo - * sob os termos da Licenחa Pתblica Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versדo 2 da Licenחa, como (a seu critיrio) - * qualquer versדo posterior. - * - * Este programa י distribuם­do na expectativa de que seja תtil, porיm, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implם­cita de COMERCIABILIDADE OU - * ADEQUAֳַO A UMA FINALIDADE ESPECֽFICA. Consulte a Licenחa Pתblica Geral - * do GNU para mais detalhes. - * - * Vocך deve ter recebido uma cףpia da Licenחa Pתblica Geral do GNU junto - * com este programa; se nדo, escreva para a Free Software Foundation, Inc., no - * endereחo 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixדo - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Arquivo disponםvel desde a versדo 1.1.0 - * @version $Id$ - */ - require_once 'Core/View/Tabulable.php'; require_once 'include/clsListagem.inc.php'; require_once 'CoreExt/View/Helper/UrlHelper.php'; -/** - * Core_Controller_Page_ListController abstract class. - * - * Provך um controller padrדo para listagem de registros. - * - * @author Eriksen Costa Paixדo - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Classe disponםvel desde a versדo 1.1.0 - * @version @@package_version@@ - */ class Core_Controller_Page_ListController extends clsListagem implements Core_View_Tabulable { - /** - * Mapeia um nome descritivo a um atributo de CoreExt_Entity retornado pela - * instגncia CoreExt_DataMapper retornada por getDataMapper(). - * - * Para uma instגncia de CoreExt_Entity que tenha os seguintes atributos: - * - * NULL - * 'idade' => NULL, - * 'data_validacao' => NULL - * ); - * - * - * O mapeamento poderia ser feito da seguinte forma: - * - * 'nome', - * 'Idade (anos)' => 'idade' - * ); - * - * - * Se um atributo nדo for mapeado, ele nדo serב exibido por padrדo durante - * a geraחדo de HTML na execuחדo do mיtodo Gerar(). - * - * @var array - */ - protected $_tableMap = array(); - - /** - * Getter. - * @see Core_View_Tabulable#getTableMap() - */ - public function getTableMap() - { - return $this->_tableMap; - } - - /** - * Retorna os registros a serem exibidos na listagem. - * - * Subclasses devem sobrescrever este mיtodo quando os parגmetros para - * CoreExt_DataMapper::findAll forem mais especםficos. - * - * @return array (int => CoreExt_Entity) - */ - public function getEntries() - { - $mapper = $this->getDataMapper(); - return $mapper->findAll(); - } - - /** - * Configura o botדo de aחדo padrדo para a criaחדo de novo registro. - */ - public function setAcao() - { - $obj_permissao = new clsPermissoes(); - - if($obj_permissao->permissao_cadastra($this->_processoAp, $this->getPessoaLogada(),7,null,true)) + /** + * Mapeia um nome descritivo a um atributo de CoreExt_Entity retornado pela + * instגncia CoreExt_DataMapper retornada por getDataMapper(). + * + * Para uma instגncia de CoreExt_Entity que tenha os seguintes atributos: + * + * NULL + * 'idade' => NULL, + * 'data_validacao' => NULL + * ); + * + * + * O mapeamento poderia ser feito da seguinte forma: + * + * 'nome', + * 'Idade (anos)' => 'idade' + * ); + * + * + * Se um atributo nדo for mapeado, ele nדo serב exibido por padrדo durante + * a geraחדo de HTML na execuחדo do mיtodo Gerar(). + * + * @var array + */ + protected $_tableMap = []; + + /** + * Getter. + * + * @see Core_View_Tabulable#getTableMap() + */ + public function getTableMap() + { + return $this->_tableMap; + } + + /** + * Retorna os registros a serem exibidos na listagem. + * + * Subclasses devem sobrescrever este mיtodo quando os parגmetros para + * CoreExt_DataMapper::findAll forem mais especםficos. + * + * @return array (int => CoreExt_Entity) + * + * @throws Core_Controller_Page_Exception + */ + public function getEntries() + { + $mapper = $this->getDataMapper(); + + return $mapper->findAll(); + } + + /** + * Configura o botדo de aחדo padrדo para a criaחדo de novo registro. + */ + public function setAcao() { - $this->acao = 'go("edit")'; - $this->nome_acao = 'Novo'; + $obj_permissao = new clsPermissoes(); + + if ($obj_permissao->permissao_cadastra($this->_processoAp, $this->getPessoaLogada(), 7, null, true)) { + $this->acao = 'go("edit")'; + $this->nome_acao = 'Novo'; + } } - } - - protected function getPessoaLogada(){ - return $_SESSION['id_pessoa']; - } - - /** - * Implementaחדo padrדo para as subclasses que estenderem essa classe. Cria - * uma lista de apresentaחדo de dados simples utilizando o mapeamento de - * $_tableMap. - * - * @see Core_Controller_Page_ListController#$_tableMap - * @see clsDetalhe#Gerar() - */ - public function Gerar() - { - $headers = $this->getTableMap(); - - // Configura o cabeחalho da listagem. - $this->addCabecalhos(array_keys($headers)); - - // Recupera os registros para a listagem. - $entries = $this->getEntries(); - - // Paginador - $this->limite = 20; - $this->offset = ($_GET['pagina_' . $this->nome]) ? - $_GET['pagina_' . $this->nome] * $this->limite - $this->limite - : 0; - - foreach ($entries as $entry) { - $item = array(); - $data = $entry->toArray(); - $options = array('query' => array('id' => $entry->id)); - - foreach ($headers as $label => $attr) { - $item[] = CoreExt_View_Helper_UrlHelper::l( - $entry->$attr, 'view', $options - ); - } - - $this->addLinhas($item); + + protected function getPessoaLogada() + { + return $_SESSION['id_pessoa']; } - $this->addPaginador2('', count($entries), $_GET, $this->nome, $this->limite); + /** + * Implementaחדo padrדo para as subclasses que estenderem essa classe. Cria + * uma lista de apresentaחדo de dados simples utilizando o mapeamento de + * $_tableMap. + * + * @see Core_Controller_Page_ListController#$_tableMap + * @see clsDetalhe#Gerar() + */ + public function Gerar() + { + $headers = $this->getTableMap(); + + // Configura o cabeחalho da listagem. + $this->addCabecalhos(array_keys($headers)); + + // Recupera os registros para a listagem. + $entries = $this->getEntries(); + + // Paginador + $this->limite = 20; + $this->offset = ($_GET['pagina_' . $this->nome]) + ? $_GET['pagina_' . $this->nome] * $this->limite - $this->limite + : 0; - // Configura o botדo padrדo de aחדo para a criaחדo de novo registro. - $this->setAcao(); + foreach ($entries as $entry) { + $item = []; + $data = $entry->toArray(); + $options = ['query' => ['id' => $entry->id]]; - // Largura da tabela HTML onde se encontra a listagem. - $this->largura = '100%'; - } + foreach ($headers as $label => $attr) { + $item[] = CoreExt_View_Helper_UrlHelper::l( + $entry->$attr, + 'view', + $options + ); + } + + $this->addLinhas($item); + } + + $this->addPaginador2('', count($entries), $_GET, $this->nome, $this->limite); + + // Configura o botדo padrדo de aחדo para a criaחדo de novo registro. + $this->setAcao(); + + // Largura da tabela HTML onde se encontra a listagem. + $this->largura = '100%'; + } } diff --git a/ieducar/lib/Core/Controller/Page/Validatable.php b/ieducar/lib/Core/Controller/Page/Validatable.php index 31a5583a1c..80366cc31b 100644 --- a/ieducar/lib/Core/Controller/Page/Validatable.php +++ b/ieducar/lib/Core/Controller/Page/Validatable.php @@ -1,48 +1,11 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * Core_Controller_Page_Validatable interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface Core_Controller_Page_Validatable { - /** - * Retorna um array com objetos CoreExt_Validate. - * @return array - */ - public function getValidators(); + /** + * Retorna um array com objetos CoreExt_Validate. + * + * @return array + */ + public function getValidators(); } diff --git a/ieducar/lib/Core/Controller/Page/ViewController.php b/ieducar/lib/Core/Controller/Page/ViewController.php index 97c0c0574b..18964ffbdb 100644 --- a/ieducar/lib/Core/Controller/Page/ViewController.php +++ b/ieducar/lib/Core/Controller/Page/ViewController.php @@ -1,192 +1,152 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'Core/View/Tabulable.php'; require_once 'include/clsDetalhe.inc.php'; require_once 'CoreExt/View/Helper/UrlHelper.php'; require_once 'Portabilis/View/Helper/Application.php'; -/** - * Core_Controller_Page_ViewController abstract class. - * - * Provê um controller padrão para a visualização de um registro. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class Core_Controller_Page_ViewController extends clsDetalhe implements Core_View_Tabulable { - /** - * Mapeia um nome descritivo a um atributo de CoreExt_Entity retornado pela - * instância CoreExt_DataMapper retornada por getDataMapper(). - * - * Para uma instância de CoreExt_Entity que tenha os seguintes atributos: - * - * NULL - * 'idade' => NULL, - * 'data_validacao' => NULL - * ); - * - * - * O mapeamento poderia ser feito da seguinte forma: - * - * 'nome', - * 'Idade (anos)' => 'idade' - * ); - * - * - * Se um atributo não for mapeado, ele não será exibido por padrão durante - * a geração de HTML na execução do método Gerar(). - * - * @var array - */ - protected $_tableMap = array(); - - /** - * Construtor. - * @todo Criar interface de hooks semelhante ao controller Edit. - */ - public function __construct() - { - $this->titulo = $this->getBaseTitulo(); - $this->largura = "100%"; - } - - /** - * Getter. - * @see Core_View_Tabulable#getTableMap() - */ - public function getTableMap() - { - return $this->_tableMap; - } - - /** - * Configura a URL padrão para a ação de Edição de um registro. - * - * Por padrão, cria uma URL "edit/id", onde id é o valor do atributo "id" - * de uma instância CoreExt_Entity. - * - * @param CoreExt_Entity $entry A instância atual recuperada - * ViewController::Gerar(). - */ - public function setUrlEditar(CoreExt_Entity $entry) - { - if($this->_hasPermissaoCadastra()) - $this->url_editar = CoreExt_View_Helper_UrlHelper::url( - 'edit', array('query' => array('id' => $entry->id)) - ); - } - - /** - * Configura a URL padrão para a ação Cancelar da tela de Edição de um - * registro. - * - * Por padrão, cria uma URL "index". - * - * @param CoreExt_Entity $entry A instância atual recuperada - * ViewController::Gerar(). - */ - public function setUrlCancelar(CoreExt_Entity $entry) - { - $this->url_cancelar = CoreExt_View_Helper_UrlHelper::url('index'); - } - - /** - * Implementação padrão para as subclasses que estenderem essa classe. Cria - * uma tela de apresentação de dados simples utilizando o mapeamento de - * $_tableMap. - * - * @see Core_Controller_Page_ViewController#$_tableMap - * @see clsDetalhe#Gerar() - */ - - /** - * Getter. - * @return clsPermissoes - */ - public function getClsPermissoes() - { - require_once 'include/pmieducar/clsPermissoes.inc.php'; - return new clsPermissoes(); - } - - /** - * Verifica se o usuário possui privilégios de cadastro para o processo. - * @return bool|void Redireciona caso a opção 'nivel_acesso_insuficiente' seja - * diferente de NULL. - */ - protected function _hasPermissaoCadastra() - { - return $this->getClsPermissoes()->permissao_cadastra( - $this->getBaseProcessoAp(), - $this->getPessoaLogada(), - 7 - ); - } - - protected function getPessoaLogada(){ - return $_SESSION['id_pessoa']; - } - - public function Gerar() - { - $headers = $this->getTableMap(); - $mapper = $this->getDataMapper(); - - $this->titulo = $this->getBaseTitulo(); - $this->largura = "100%"; - - try { - $entry = $mapper->find($this->getRequest()->id); - } catch (Exception $e) { - $this->mensagem = $e; - return FALSE; + /** + * Mapeia um nome descritivo a um atributo de CoreExt_Entity retornado pela + * instância CoreExt_DataMapper retornada por getDataMapper(). + * + * Para uma instância de CoreExt_Entity que tenha os seguintes atributos: + * + * NULL + * 'idade' => NULL, + * 'data_validacao' => NULL + * ); + * + * + * O mapeamento poderia ser feito da seguinte forma: + * + * 'nome', + * 'Idade (anos)' => 'idade' + * ); + * + * + * Se um atributo não for mapeado, ele não será exibido por padrão durante + * a geração de HTML na execução do método Gerar(). + * + * @var array + */ + protected $_tableMap = []; + + /** + * Construtor. + */ + public function __construct() + { + $this->titulo = $this->getBaseTitulo(); + $this->largura = '100%'; + } + + /** + * Getter. + * + * @see Core_View_Tabulable#getTableMap() + */ + public function getTableMap() + { + return $this->_tableMap; + } + + /** + * Configura a URL padrão para a ação de Edição de um registro. + * + * Por padrão, cria uma URL "edit/id", onde id é o valor do atributo "id" + * de uma instância CoreExt_Entity. + * + * @param CoreExt_Entity $entry A instância atual recuperada + * ViewController::Gerar(). + */ + public function setUrlEditar(CoreExt_Entity $entry) + { + if ($this->_hasPermissaoCadastra()) { + $this->url_editar = CoreExt_View_Helper_UrlHelper::url( + 'edit', + ['query' => ['id' => $entry->id]] + ); + } + } + + /** + * Configura a URL padrão para a ação Cancelar da tela de Edição de um + * registro. + * + * Por padrão, cria uma URL "index". + * + * @param CoreExt_Entity $entry A instância atual recuperada + * ViewController::Gerar(). + */ + public function setUrlCancelar(CoreExt_Entity $entry) + { + $this->url_cancelar = CoreExt_View_Helper_UrlHelper::url('index'); + } + + /** + * Getter. + * + * @return clsPermissoes + */ + public function getClsPermissoes() + { + require_once 'include/pmieducar/clsPermissoes.inc.php'; + + return new clsPermissoes(); + } + + /** + * Verifica se o usuário possui privilégios de cadastro para o processo. + * + * @return bool|void Redireciona caso a opção 'nivel_acesso_insuficiente' seja + * diferente de NULL. + * + * @throws Core_Controller_Page_Exception + */ + protected function _hasPermissaoCadastra() + { + return $this->getClsPermissoes()->permissao_cadastra( + $this->getBaseProcessoAp(), + $this->getPessoaLogada(), + 7 + ); } - foreach ($headers as $label => $attr) { - $value = $entry->$attr; - if (!is_null($value)) { - $this->addDetalhe(array($label, $value)); - } + protected function getPessoaLogada() + { + return $_SESSION['id_pessoa']; } - $this->setUrlEditar($entry); - $this->setUrlCancelar($entry); - } -} \ No newline at end of file + public function Gerar() + { + $headers = $this->getTableMap(); + $mapper = $this->getDataMapper(); + + $this->titulo = $this->getBaseTitulo(); + $this->largura = '100%'; + + try { + $entry = $mapper->find($this->getRequest()->id); + } catch (Exception $e) { + $this->mensagem = $e; + + return false; + } + + foreach ($headers as $label => $attr) { + $value = $entry->$attr; + if (!is_null($value)) { + $this->addDetalhe([$label, $value]); + } + } + + $this->setUrlEditar($entry); + $this->setUrlCancelar($entry); + } +} diff --git a/ieducar/lib/Core/View.php b/ieducar/lib/Core/View.php index 3436137cea..bcccaa6e6d 100644 --- a/ieducar/lib/Core/View.php +++ b/ieducar/lib/Core/View.php @@ -1,150 +1,128 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_View - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'include/clsBase.inc.php'; -/** - * Core_View class. - * - * Provê métodos getters/setters e alguns métodos sobrescritos para facilitar - * a geração de páginas usando CoreExt_Controller_Page_Interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_View - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class Core_View extends clsBase { - /** - * Uma instância de CoreExt_Controller_Page_Interface. - * @var CoreExt_Controller_Page_Interface - */ - protected $_pageController = NULL; - - /** - * Construtor. - * @param Core_Controller_Page_Interface $instance - */ - public function __construct(Core_Controller_Page_Interface $instance) - { - parent::__construct(); - $this->_setPageController($instance); - } - - /** - * Setter. - * @param Core_Controller_Page_Interface $instance - * @return Core_View Provê interface fluída - */ - protected function _setPageController(Core_Controller_Page_Interface $instance) - { - $this->_pageController = $instance; - return $this; - } - - /** - * Getter. - * @return CoreExt_Controller_Page_Interface - */ - protected function _getPageController() - { - return $this->_pageController; - } - - /** - * Setter - * @param string $titulo - * @return Core_View Provê interface fluída - */ - public function setTitulo($titulo) - { - parent::SetTitulo($titulo); - return $this; - } - - /** - * Getter. - * @return string - */ - public function getTitulo() - { - return $this->titulo; - } - - /** - * Setter. - * @param int $processo - * @return Core_View Provê interface fluída - */ - public function setProcessoAp($processo) - { - $this->processoAp = (int) $processo; - return $this; - } - - /** - * Getter. - * @return int - */ - public function getProcessoAp() - { - return $this->processoAp; - } - - /** - * Configura algumas variáveis de instância usando o container global - * $coreExt. - * - * @global $coreExt - * @see clsBase#Formular() - */ - public function Formular() - { - global $coreExt; - $instituicao = $coreExt['Config']->app->template->vars->instituicao; - - $this->setTitulo($instituicao . ' | ' . $this->_getPageController()->getBaseTitulo()) - ->setProcessoAp($this->_getPageController()->getBaseProcessoAp()); - } - - /** - * Executa o método de geração de HTML para a classe. - * @param Core_View $instance - */ - public static function generate($instance) - { - $viewBase = new self($instance); - $viewBase->addForm($instance); - $viewBase->MakeAll(); - } + /** + * Uma instância de CoreExt_Controller_Page_Interface. + * + * @var CoreExt_Controller_Page_Interface + */ + protected $_pageController = null; + + /** + * Construtor. + * + * @param Core_Controller_Page_Interface $instance + */ + public function __construct(Core_Controller_Page_Interface $instance) + { + parent::__construct(); + + $this->_setPageController($instance); + } + + /** + * Setter. + * + * @param Core_Controller_Page_Interface $instance + * + * @return Core_View Provê interface fluída + */ + protected function _setPageController(Core_Controller_Page_Interface $instance) + { + $this->_pageController = $instance; + + return $this; + } + + /** + * Getter. + * + * @return CoreExt_Controller_Page_Interface + */ + protected function _getPageController() + { + return $this->_pageController; + } + + /** + * Setter + * + * @param string $titulo + * + * @return Core_View Provê interface fluída + */ + public function setTitulo($titulo) + { + parent::SetTitulo($titulo); + + return $this; + } + + /** + * Getter. + * + * @return string + */ + public function getTitulo() + { + return $this->titulo; + } + + /** + * Setter. + * + * @param int $processo + * + * @return Core_View Provê interface fluída + */ + public function setProcessoAp($processo) + { + $this->processoAp = (int) $processo; + + return $this; + } + + /** + * Getter. + * + * @return int + */ + public function getProcessoAp() + { + return $this->processoAp; + } + + /** + * Configura algumas variáveis de instância usando o container global + * $coreExt. + * + * @global $coreExt + * + * @see clsBase#Formular() + */ + public function Formular() + { + global $coreExt; + $instituicao = $coreExt['Config']->app->template->vars->instituicao; + + $this->setTitulo($instituicao . ' | ' . $this->_getPageController()->getBaseTitulo()) + ->setProcessoAp($this->_getPageController()->getBaseProcessoAp()); + } + + /** + * Executa o método de geração de HTML para a classe. + * + * @param Core_View $instance + * + * @throws Exception + */ + public static function generate($instance) + { + $viewBase = new self($instance); + $viewBase->addForm($instance); + $viewBase->MakeAll(); + } } diff --git a/ieducar/lib/Core/View/Tabulable.php b/ieducar/lib/Core/View/Tabulable.php index ee0c514715..89219a1b9c 100644 --- a/ieducar/lib/Core/View/Tabulable.php +++ b/ieducar/lib/Core/View/Tabulable.php @@ -1,50 +1,11 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_View - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * Core_View_Tabulable interface. - * - * Provê uma API para criar listagem de itens tabulados. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package Core_View - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface Core_View_Tabulable { - /** - * Retorna um array associativo no formato nome do campo => label. - * @return array - */ - public function getTableMap(); + /** + * Retorna um array associativo no formato nome do campo => label. + * + * @return array + */ + public function getTableMap(); } diff --git a/ieducar/lib/CoreExt/Config.class.php b/ieducar/lib/CoreExt/Config.class.php index 0eedb334da..2fa9e4879b 100644 --- a/ieducar/lib/CoreExt/Config.class.php +++ b/ieducar/lib/CoreExt/Config.class.php @@ -1,271 +1,233 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - */ - -/** - * CoreExt_Config class. - * - * Transforma um array comum em um objeto CoreExt_Config, permitindo que esse - * array seja acessado com o operador ->, assim como variáveis de instância. - * Dessa forma, um array como: - * - * - * $array = array( - * 'app' => array( - * 'database' => array( - * 'dbname' => 'ieducar', - * 'hostname' => 'localhost', - * 'password' => 'ieducar', - * 'username' => 'ieducar', - * ) - * ), - * 'CoreExt' => '1' - * ) - * - * - * Pode ser acessado dessa forma: - * - * - * $config = new CoreExt_Config($array); - * print $config->app->database->dbname; - * - * - * Essa classe foi fortemente baseada na classe Zend_Config do Zend Framework só - * que implementa menos funcionalidades. - * - * @author Eriksen Costa Paixão - * @license http://creativecommons.org/licenses/GPL/2.0/legalcode.pt CC GNU GPL - * @package CoreExt - * @subpackage Config - * @since Classe disponível desde a versão 1.1.0 - * @version $Id$ - */ class CoreExt_Config implements Countable, Iterator { - /** - * Array de sobre sobrecarga - * @var array - */ - protected $config; + /** + * Array de sobre sobrecarga + * + * @var array + */ + protected $config; + + /** + * Array com mensagens de erro causadas por funções PHP. + * + * @var array + */ + protected $errors = []; + + /** + * Índice interno do array para a implementação da interface Iterator. + * + * @var int + */ + private $_index = 0; + + /** + * Quantidade de items do array de sobrecarga $config para a implementação da interface Countable. + * + * @var int + */ + private $_count = 0; + + /** + * Construtor da classe. + * + * @param $array Array associativo com as diretivas de configuração. + */ + public function __construct($array) + { + foreach ($array as $key => $val) { + if (is_array($val)) { + $this->config[$key] = new self($val); + } else { + $this->config[$key] = $val; + } + } - /** - * Array com mensagens de erro causadas por funções PHP. - * @var array - */ - protected $errors = array(); + $this->_count = count($this->config); + } - /** - * Índice interno do array para a implementação da interface Iterator. - * @var int - */ - private $_index = 0; + /** + * Retorna o valor do array de sobrecarga $config. + * + * Este método deve ser usado toda vez que a variável de configuração puder + * ser sobrescrita por um storage de configuração externa ao código, como o + * arquivo ini. Um exemplo seria para a criação de um arquivo on the fly no + * filesystem. No código pode ser assumido que o local padrão será + * intranet/tmp mas, se esse valor puder ser sobrescrito pelo ini, esse método + * deverá ser utilizado: + * + * $dir = $config->get($config->app->filesystem->tmp_dir, 'intranet/tmp'); + * + * + * Se a variável de configuração não for sobrescrita por um arquivo ini ou + * array de configuração, o valor padrão (segundo parâmetro) será utilizado. + * + * @param mixed $value1 Valor retornado pelo array de configuração sobrecarregado + * @param mixed $value2 Valor padrão caso não exista uma configuração sobrecarregada + * + * @return mixed + * + * @throws Exception + */ + public function get($value1, $value2 = null) + { + if (null != $value1) { + return $value1; + } - /** - * Quantidade de items do array de sobrecarga $config para a implementação da interface Countable. - * @var int - */ - private $_count = 0; + if (null == $value2) { + throw new Exception('O segundo parâmetro deve conter algum valor não nulo.'); + } - /** - * Construtor da classe. - * - * @param $array Array associativo com as diretivas de configuração. - */ - public function __construct($array) - { - foreach ($array as $key => $val) { - if (is_array($val)) { - $this->config[$key] = new self($val); - } - else { - $this->config[$key] = $val; - } + return $value2; } - $this->_count = count($this->config); - } + /** + * Retorna o valor armazenado pelo índice no array de sobrecarga $config. + * + * @param $key Índice (nome) da variável criada por sobrecarga + * @param $value Valor padrão caso o índice não exista + * + * @return mixed O valor armazenado em + */ + private function getFrom($key, $value = null) + { + if (array_key_exists($key, $this->config)) { + $value = $this->config[$key]; + } - /** - * Retorna o valor do array de sobrecarga $config. - * - * Este método deve ser usado toda vez que a variável de configuração puder - * ser sobrescrita por um storage de configuração externa ao código, como o - * arquivo ini. Um exemplo seria para a criação de um arquivo on the fly no - * filesystem. No código pode ser assumido que o local padrão será - * intranet/tmp mas, se esse valor puder ser sobrescrito pelo ini, esse método - * deverá ser utilizado: - * - * $dir = $config->get($config->app->filesystem->tmp_dir, 'intranet/tmp'); - * - * - * Se a variável de configuração não for sobrescrita por um arquivo ini ou - * array de configuração, o valor padrão (segundo parâmetro) será utilizado. - * - * @param mixed $value1 Valor retornado pelo array de configuração sobrecarregado - * @param mixed $value2 Valor padrão caso não exista uma configuração sobrecarregada - * @return mixed - */ - public function get($value1, $value2 = NULL) - { - if (NULL != $value1) { - return $value1; + return $value; } - if (NULL == $value2) { - throw new Exception('O segundo parâmetro deve conter algum valor não nulo.'); + /** + * Implementação do método mágico __get(). + * + * @param $key + * + * @return unknown_type + */ + public function __get($key) + { + return $this->getFrom($key); } - return $value2; - } + /** + * Retorna o conteúdo do array de sobrecarga em um array associativo simples. + * + * @return array + */ + public function toArray() + { + $array = []; + foreach ($this->config as $key => $value) { + $array[$key] = $value; + } - /** - * Retorna o valor armazenado pelo índice no array de sobrecarga $config. - * - * @param $key Índice (nome) da variável criada por sobrecarga - * @param $value Valor padrão caso o índice não exista - * @return mixed O valor armazenado em - */ - private function getFrom($key, $value = NULL) - { - if (array_key_exists($key, $this->config)) { - $value = $this->config[$key]; + return $array; } - return $value; - } - - /** - * Implementação do método mágico __get(). - * - * @param $key - * @return unknown_type - */ - public function __get($key) { - return $this->getFrom($key); - } - - /** - * Retorna o conteúdo do array de sobrecarga em um array associativo simples. - * @return array - */ - public function toArray() - { - $array = array(); - foreach ($this->config as $key => $value) { - $array[$key] = $value; + /** + * Implementação do método count() da interface Countable. + */ + public function count() + { + return $this->_count; } - return $array; - } - - /** - * Implementação do método count() da interface Countable. - */ - public function count() { - return $this->_count; - } - - /** - * Implementação do método next() da interface Iterator. - */ - public function next() { - next($this->config); - ++$this->_index; - } - /** - * Implementação do método next() da interface Iterator. - */ - public function rewind() { - reset($this->config); - $this->_index = 0; - } - - /** - * Implementação do método current() da interface Iterator. - */ - public function current() { - return current($this->config); - } + /** + * Implementação do método next() da interface Iterator. + */ + public function next() + { + next($this->config); + ++$this->_index; + } - /** - * Implementação do método key() da interface Iterator. - */ - public function key() { - return key($this->config); - } + /** + * Implementação do método next() da interface Iterator. + */ + public function rewind() + { + reset($this->config); + $this->_index = 0; + } - /** - * Implementação do método valid() da interface Iterator. - */ - public function valid() { - return $this->_index < $this->_count && $this->_index > -1; - } + /** + * Implementação do método current() da interface Iterator. + */ + public function current() + { + return current($this->config); + } - /** - * Merge recursivo mantendo chaves distintas. - * - * Realiza um merge recursivo entre dois arrays. É semelhante a função PHP - * {@link http://php.net/array_merge_recursive array_merge_recursive} exceto - * pelo fato de que esta mantém apenas um valor de uma chave do array ao invés - * de criar múltiplos valores para a mesma chave como na função original. - * - * @author Daniel Smedegaard Buus - * @link http://www.php.net/manual/pt_BR/function.array-merge-recursive.php#89684 Código fonte original - * @param array $arr1 - * @param array $arr2 - * @return array - */ - protected function &arrayMergeRecursiveDistinct(&$arr1, &$arr2) - { - $merged = $arr1; + /** + * Implementação do método key() da interface Iterator. + */ + public function key() + { + return key($this->config); + } - if (is_array($arr2)) { - foreach ($arr2 as $key => $val) { - if (is_array($arr2[$key])) { - $merged[$key] = isset($merged[$key]) && is_array($merged[$key]) ? - $this->arrayMergeRecursiveDistinct($merged[$key], $arr2[$key]) : $arr2[$key]; - } - else { - $merged[$key] = $val; - } - } + /** + * Implementação do método valid() da interface Iterator. + */ + public function valid() + { + return $this->_index < $this->_count && $this->_index > -1; } - return $merged; - } + /** + * Merge recursivo mantendo chaves distintas. + * + * Realiza um merge recursivo entre dois arrays. É semelhante a função PHP + * {@link http://php.net/array_merge_recursive array_merge_recursive} exceto + * pelo fato de que esta mantém apenas um valor de uma chave do array ao invés + * de criar múltiplos valores para a mesma chave como na função original. + * + * @author Daniel Smedegaard Buus + * + * @link http://www.php.net/manual/pt_BR/function.array-merge-recursive.php#89684 Código fonte original + * + * @param array $arr1 + * @param array $arr2 + * + * @return array + */ + protected function &arrayMergeRecursiveDistinct(&$arr1, &$arr2) + { + $merged = $arr1; + + if (is_array($arr2)) { + foreach ($arr2 as $key => $val) { + if (is_array($arr2[$key])) { + $merged[$key] = isset($merged[$key]) && is_array($merged[$key]) + ? $this->arrayMergeRecursiveDistinct($merged[$key], $arr2[$key]) + : $arr2[$key]; + } else { + $merged[$key] = $val; + } + } + } - /** - * Método callback para a função set_error_handler(). - * - * Handler para os erros internos da classe. Dessa forma, é possível usar - * os blocos try/catch para lançar exceções. - * - * @see http://php.net/set_error_handler - * @param $errno - * @param $errstr - */ - protected function configErrorHandler($errno, $errstr) { - $this->errors[] = array($errno => $errstr); - } + return $merged; + } -} \ No newline at end of file + /** + * Método callback para a função set_error_handler(). + * + * Handler para os erros internos da classe. Dessa forma, é possível usar + * os blocos try/catch para lançar exceções. + * + * @see http://php.net/set_error_handler + * + * @param $errno + * @param $errstr + */ + protected function configErrorHandler($errno, $errstr) + { + $this->errors[] = [$errno => $errstr]; + } +} diff --git a/ieducar/lib/CoreExt/Config/Ini.class.php b/ieducar/lib/CoreExt/Config/Ini.class.php index a407974c2c..d9e2bc5de6 100644 --- a/ieducar/lib/CoreExt/Config/Ini.class.php +++ b/ieducar/lib/CoreExt/Config/Ini.class.php @@ -1,260 +1,229 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - */ -/** - * CoreExt_Config_Ini class. - * - * Essa classe torna possível o uso de um arquivo .ini como meio de configuração - * da aplicação. O parsing do arquivo é feito através da função PHP nativa - * parse_ini_file. Possibilita o uso de herança simples e separação de - * namespaces no arquivo ini, tornando simples a criação de diferentes espaços - * de configuração para o uso em ambientes diversos como produção, - * desenvolvimento, testes e outros. - * - * Para o uso dessa classe, é necessário que o arquivo ini tenha no mínimo uma - * seção de configuração. A seção padrão a ser usada é a production mas isso - * não impede que você a nomeie como desejar. - * - * Essa classe foi fortemente baseada na classe Zend_Config_Ini do Zend - * Framework. - * - * @author Eriksen Costa Paixão - * @license http://creativecommons.org/licenses/GPL/2.0/legalcode.pt CC GNU GPL - * @package CoreExt - * @subpackage Config - * @see lib/CoreExt/Config.class.php - * @since Classe disponível desde a versão 1.1.0 - * @version $Id$ - */ class CoreExt_Config_Ini extends CoreExt_Config { + /** + * Caractere de herança das seções do arquivo ini. + */ + const COREEXT_CONFIG_INI_INHERITANCE_SEP = ':'; - /** - * Caractere de herança das seções do arquivo ini. - */ - const COREEXT_CONFIG_INI_INHERITANCE_SEP = ':'; - - /** - * Caractere de namespace das diretivas do arquivo ini. - */ - const COREEXT_CONFIG_INI_NAMESPACE_SEP = '.'; - - /** - * Array contendo as diretivas de configuração separadas por namespace. - * @var array - */ - protected $iniArr = array(); - - /** - * Construtor. - * - * @param $filename Caminho para o arquivo ini - * @param $section Seção desejada para o carregamento das configurações - */ - public function __construct($filename, $section = 'production') - { - require_once 'CoreExt/Config.class.php'; - - $this->iniArr = $this->loadFile($filename); - parent::__construct($this->iniArr[$section]); - } - - /** - * Carrega as configurações para o ambiente desejado (seção do arquivo ini) - * @param string $section - */ - public function changeEnviroment($section = 'production') { - $this->changeSection($section); - } + /** + * Caractere de namespace das diretivas do arquivo ini. + */ + const COREEXT_CONFIG_INI_NAMESPACE_SEP = '.'; - /** - * Verifica se possui a seção desejada. - * @param string $section - */ - function hasEnviromentSection($section) { - return isset($this->iniArr[$section]) && is_array($this->iniArr[$section]); - } + /** + * Array contendo as diretivas de configuração separadas por namespace. + * + * @var array + */ + protected $iniArr = []; + + /** + * Construtor. + * + * @param string $filename Caminho para o arquivo ini + * @param string $section Seção desejada para o carregamento das configurações + * + * @throws Exception + */ + public function __construct($filename, $section = 'production') + { + require_once 'CoreExt/Config.class.php'; - /** - * Carrega as configuração da seção desejada. - * @param string $section - */ - protected function changeSection($section = 'production') { - parent::__construct($this->iniArr[$section]); - } + $this->iniArr = $this->loadFile($filename); - /** - * Parsing do arquivo ini. - * - * Realiza o parsing do arquivo ini, separando as seções, criando as relações - * de herança e separando cada diretiva do arquivo em um array - * multidimensional. - * - * @link http://php.net/parse_ini_file Documentação da função parse_ini_file - * @param string $filename - * @throws Exception - * @return array - */ - private function loadFile($filename) - { - $iniArr = array(); + parent::__construct($this->iniArr[$section]); + } - // Faz o parsing separando as seções (parâmetro TRUE) - // Supressão simples dificulta os unit test. Altera o error handler para - // que use um método da classe CoreExt_Config. - set_error_handler(array($this, 'configErrorHandler'), E_ALL); - $config = parse_ini_file($filename, TRUE); - restore_error_handler(); + /** + * Carrega as configurações para o ambiente desejado (seção do arquivo ini) + * + * @param string $section + */ + public function changeEnviroment($section = 'production') + { + $this->changeSection($section); + } - /* - * No PHP 5.2.7 o array vem FALSE quando existe um erro de sintaxe. Antes - * o retorno vinha como array vazio. - * @link http://php.net/parse_ini_file#function.parse-ini-file.changelog Changelog da função parse_ini_file + /** + * Verifica se possui a seção desejada. + * + * @param string $section + * + * @return bool */ - if (count($this->errors) > 0) { - throw new Exception('Arquivo ini com problemas de sintaxe. Verifique a sintaxe arquivo \''. $filename .'\'.'); + public function hasEnviromentSection($section) + { + return isset($this->iniArr[$section]) && is_array($this->iniArr[$section]); } - foreach ($config as $section => $data) { - $index = $section; + /** + * Carrega as configuração da seção desejada. + * + * @param string $section + */ + protected function changeSection($section = 'production') + { + parent::__construct($this->iniArr[$section]); + } - if (FALSE !== strpos($section, self::COREEXT_CONFIG_INI_INHERITANCE_SEP)) { - $sections = explode(self::COREEXT_CONFIG_INI_INHERITANCE_SEP, $section); - // Apenas uma herança por seção é permitida - if (count($sections) > 2) { - throw new Exception('Não é possível herdar mais que uma seção.'); + /** + * Parsing do arquivo ini. + * + * Realiza o parsing do arquivo ini, separando as seções, criando as relações + * de herança e separando cada diretiva do arquivo em um array + * multidimensional. + * + * @link http://php.net/parse_ini_file Documentação da função parse_ini_file + * + * @param string $filename + * + * @throws Exception + * + * @return array + */ + private function loadFile($filename) + { + $iniArr = []; + + // Faz o parsing separando as seções (parâmetro TRUE) + // Supressão simples dificulta os unit test. Altera o error handler para + // que use um método da classe CoreExt_Config. + set_error_handler([$this, 'configErrorHandler'], E_ALL); + $config = parse_ini_file($filename, true); + restore_error_handler(); + + /* + * No PHP 5.2.7 o array vem FALSE quando existe um erro de sintaxe. Antes + * o retorno vinha como array vazio. + * @link http://php.net/parse_ini_file#function.parse-ini-file.changelog Changelog da função parse_ini_file + */ + if (count($this->errors) > 0) { + throw new Exception('Arquivo ini com problemas de sintaxe. Verifique a sintaxe arquivo \'' . $filename . '\'.'); } - // Armazena seção atual e seção de herança - $section = trim($sections[0]); - $extends = trim($sections[1]); - } - - // Processa as diretivas da seção atual para separarar os namespaces - $iniArr[$section] = $this->processSection($config[$index]); - - /* - * Verifica se a seção atual herda de alguma outra seção. Se a seção de - * herança não existir, lança uma exceção. - */ - if (isset($extends)) { - if (!array_key_exists($extends, $iniArr)) { - $message = sprintf('Não foi possível estender %s, seção %s não existe', - $section, $extends); - throw new Exception($message); + foreach ($config as $section => $data) { + $index = $section; + + if (false !== strpos($section, self::COREEXT_CONFIG_INI_INHERITANCE_SEP)) { + $sections = explode(self::COREEXT_CONFIG_INI_INHERITANCE_SEP, $section); + // Apenas uma herança por seção é permitida + if (count($sections) > 2) { + throw new Exception('Não é possível herdar mais que uma seção.'); + } + + // Armazena seção atual e seção de herança + $section = trim($sections[0]); + $extends = trim($sections[1]); + } + + // Processa as diretivas da seção atual para separarar os namespaces + $iniArr[$section] = $this->processSection($config[$index]); + + /* + * Verifica se a seção atual herda de alguma outra seção. Se a seção de + * herança não existir, lança uma exceção. + */ + if (isset($extends)) { + if (!array_key_exists($extends, $iniArr)) { + $message = sprintf( + 'Não foi possível estender %s, seção %s não existe', + $section, + $extends + ); + throw new Exception($message); + } + + // Mescla recursivamente os dois arrays. Os valores definidos na seção + // atual não são sobrescritos + $iniArr[$section] = $this->arrayMergeRecursiveDistinct($iniArr[$extends], $iniArr[$section]); + unset($extends); + } } - // Mescla recursivamente os dois arrays. Os valores definidos na seção - // atual não são sobrescritos - $iniArr[$section] = $this->arrayMergeRecursiveDistinct($iniArr[$extends], $iniArr[$section]); - unset($extends); - } + return $iniArr; } - return $iniArr; - } - - /** - * Processa uma seção de um array de arquivo ini. - * - * Processa a seção, inclusive as diretivas da seção, separando-as em - * um array em namespace. Dessa forma, uma diretiva que era, por exemplo, - * app.database.dbname = ieducardb irá se tornar: - * - * app => array(database => array(dbname => ieducardb)) - * - * - * Diretivas no mesmo namespace viram novas chaves no mesmo array: - * app.database.hostname => localhost - * - * app => array( - * database => array( - * dbname => ieducardb - * hostname => localhost - * ) - * ) - * - * - * @param array $data Array contendo as diretivas de uma seção do arquivo ini - * @return array - */ - private function processSection(array $data) - { - $entries = $data; - $config = array(); - - foreach ($entries as $key => $value) { - if (FALSE !== strpos($key, self::COREEXT_CONFIG_INI_NAMESPACE_SEP)) { - $keys = explode(self::COREEXT_CONFIG_INI_NAMESPACE_SEP, $key); - } - else { - $keys = (array) $key; - } + /** + * Processa uma seção de um array de arquivo ini. + * + * Processa a seção, inclusive as diretivas da seção, separando-as em + * um array em namespace. Dessa forma, uma diretiva que era, por exemplo, + * app.database.dbname = ieducardb irá se tornar: + * + * app => array(database => array(dbname => ieducardb)) + * + * + * Diretivas no mesmo namespace viram novas chaves no mesmo array: + * app.database.hostname => localhost + * + * app => array( + * database => array( + * dbname => ieducardb + * hostname => localhost + * ) + * ) + * + * + * @param array $data Array contendo as diretivas de uma seção do arquivo ini + * + * @return array + */ + private function processSection(array $data) + { + $entries = $data; + $config = []; + + foreach ($entries as $key => $value) { + if (false !== strpos($key, self::COREEXT_CONFIG_INI_NAMESPACE_SEP)) { + $keys = explode(self::COREEXT_CONFIG_INI_NAMESPACE_SEP, $key); + } else { + $keys = (array) $key; + } + + $config = $this->processDirectives($value, $keys, $config); + } - $config = $this->processDirectives($value, $keys, $config); + return $config; } - return $config; - } - - /** - * Cria recursivamente um array aninhado (namespaces) usando os índices - * progressivamente. - * - * Exemplo: - * - * $value = ieducardb - * $keys = array('app', 'database', 'dbname'); - * - * $config['app'] => array( - * 'database' => array( - * 'dbname' => 'ieducardb' - * ) - * ); - * - * - * @param mixed $value O valor da diretiva parseada por parse_ini_file - * @param array $keys O array contendo as chaves das diretivas (0 => app, 1 => database, 2 => dbname) - * @param array $config O array contêiner com as chaves em suas respectivas dimensões - * @return array - */ - private function processDirectives($value, $keys, $config = array()) - { - $key = array_shift($keys); - - if (count($keys) > 0) { - if (!array_key_exists($key, $config)) { - $config[$key] = array(); - } + /** + * Cria recursivamente um array aninhado (namespaces) usando os índices + * progressivamente. + * + * Exemplo: + * + * $value = ieducardb + * $keys = array('app', 'database', 'dbname'); + * + * $config['app'] => array( + * 'database' => array( + * 'dbname' => 'ieducardb' + * ) + * ); + * + * + * @param mixed $value O valor da diretiva parseada por parse_ini_file + * @param array $keys O array contendo as chaves das diretivas (0 => app, 1 => database, 2 => dbname) + * @param array $config O array contêiner com as chaves em suas respectivas dimensões + * + * @return array + */ + private function processDirectives($value, $keys, $config = []) + { + $key = array_shift($keys); + + if (count($keys) > 0) { + if (!array_key_exists($key, $config)) { + $config[$key] = []; + } + + $config[$key] = $this->processDirectives($value, $keys, $config[$key]); + } else { + $config[$key] = $value; + } - $config[$key] = $this->processDirectives($value, $keys, $config[$key]); + return $config; } - else { - $config[$key] = $value; - } - - return $config; - } - -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Configurable.php b/ieducar/lib/CoreExt/Configurable.php index 7df7ce0979..6fbcb16b42 100644 --- a/ieducar/lib/CoreExt/Configurable.php +++ b/ieducar/lib/CoreExt/Configurable.php @@ -1,91 +1,20 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Configurable - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * CoreExt_Configurable interface. - * - * Essa interface tem como objetivo prover uma API uniforme para classes que - * definem parâmetros de configuração. Basicamente provê apenas o método - * público setOptions, que recebe um array de parâmetros. Como o PHP não - * permite herança múltipla, essa API apenas reforça a idéia de se criar uma - * uniformidade entre as diferentes classes configuráveis do i-Educar. - * - * Uma sugestão de implementação do método setOptions é dada pelo exemplo a - * seguir: - * - * NULL, - * 'option2' => NULL - * ); - * - * public function setOptions(array $options = array()) - * { - * $defaultOptions = array_keys($this->getOptions()); - * $passedOptions = array_keys($options); - * - * if (0 < count(array_diff($passedOptions, $defaultOptions))) { - * throw new InvalidArgumentException( - * sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) - * ); - * } - * - * $this->_options = array_merge($this->getOptions(), $options); - * return $this; - * } - * - * public function getOptions() - * { - * return $this->_options; - * } - * - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Configurable - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Configurable { - /** - * Setter. - * @param array $options - * @return CoreExt_Configurable Provê interface fluída - */ - public function setOptions(array $options = array()); + /** + * Setter. + * + * @param array $options + * + * @return CoreExt_Configurable Provê interface fluída + */ + public function setOptions(array $options = []); - /** - * Getter. - * @return array - */ - public function getOptions(); + /** + * Getter. + * + * @return array + */ + public function getOptions(); } diff --git a/ieducar/lib/CoreExt/Controller/Abstract.php b/ieducar/lib/CoreExt/Controller/Abstract.php index 38615c3ceb..c673f8b36c 100644 --- a/ieducar/lib/CoreExt/Controller/Abstract.php +++ b/ieducar/lib/CoreExt/Controller/Abstract.php @@ -1,258 +1,240 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id: /ieducar/branches/teste/ieducar/lib/CoreExt/Controller/Front.php 645 2009-11-12T20:08:26.084511Z eriksen $ - */ - require_once 'CoreExt/Controller/Interface.php'; -/** - * CoreExt_Controller_Abstract abstract class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ abstract class CoreExt_Controller_Abstract implements CoreExt_Controller_Interface { - /** - * Uma instância de CoreExt_Controller_Request_Interface - * @var CoreExt_Controller_Request_Interface - */ - protected $_request = NULL; - - /** - * Uma instância de CoreExt_Session_Abstract - * @var CoreExt_Session_Abstract - */ - protected $_session = NULL; - - /** - * Uma instância de CoreExt_Controller_Dispatcher_Interface - * @var CoreExt_Controller_Dispatcher_Interface - */ - protected $_dispatcher = NULL; - - /** - * @see CoreExt_Configurable#setOptions($options) - */ - public function setOptions(array $options = array()) - { - $defaultOptions = array_keys($this->getOptions()); - $passedOptions = array_keys($options); - - if (0 < count(array_diff($passedOptions, $defaultOptions))) { - throw new InvalidArgumentException( - sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) - ); + /** + * Uma instância de CoreExt_Controller_Request_Interface + * + * @var CoreExt_Controller_Request_Interface + */ + protected $_request = null; + + /** + * Uma instância de CoreExt_Session_Abstract + * + * @var CoreExt_Session_Abstract + */ + protected $_session = null; + + /** + * Uma instância de CoreExt_Controller_Dispatcher_Interface + * + * @var CoreExt_Controller_Dispatcher_Interface + */ + protected $_dispatcher = null; + + /** + * @see CoreExt_Configurable#setOptions($options) + */ + public function setOptions(array $options = []) + { + $defaultOptions = array_keys($this->getOptions()); + $passedOptions = array_keys($options); + + if (0 < count(array_diff($passedOptions, $defaultOptions))) { + throw new InvalidArgumentException( + sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) + ); + } + + $this->_options = array_merge($this->getOptions(), $options); + + return $this; } - $this->_options = array_merge($this->getOptions(), $options); - return $this; - } - - /** - * @see CoreExt_Configurable#getOptions() - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Verifica se uma opção está setada. - * - * @param string $key - * @return bool - */ - protected function _hasOption($key) - { - return array_key_exists($key, $this->_options); - } - - /** - * Retorna um valor de opção de configuração ou NULL caso a opção não esteja - * setada. - * - * @param string $key - * @return mixed|NULL - */ - public function getOption($key) - { - return $this->_hasOption($key) ? $this->_options[$key] : NULL; - } - - /** - * Setter. - * @param CoreExt_Controller_Request_Interface $request - * @return CoreExt_Controller_Interface - */ - public function setRequest(CoreExt_Controller_Request_Interface $request) - { - $this->_request = $request; - return $this; - } - - /** - * Getter para uma instância de CoreExt_Controller_Request_Interface. - * - * Instância via lazy initialization uma instância de - * CoreExt_Controller_Request_Interface caso nenhuma seja explicitamente - * atribuída a instância atual. - * - * @return CoreExt_Controller_Request_Interface - */ - public function getRequest() - { - if (is_null($this->_request)) { - require_once 'CoreExt/Controller/Request.php'; - $this->setRequest(new CoreExt_Controller_Request()); + /** + * @see CoreExt_Configurable#getOptions() + */ + public function getOptions() + { + return $this->_options; } - return $this->_request; - } - - /** - * Setter. - * @param CoreExt_Session_Abstract $session - * @return CoreExt_Controller_Interface - */ - public function setSession(CoreExt_Session_Abstract $session) - { - $this->_session = $session; - return $this; - } - /** - * Getter para uma instância de CoreExt_Session. - * - * Instância via lazy initialization uma instância de CoreExt_Session caso - * nenhuma seja explicitamente atribuída a instância atual. - * - * @return CoreExt_Session - */ - public function getSession() - { - if (is_null($this->_session)) { - require_once 'CoreExt/Session.php'; - $this->setSession(new CoreExt_Session()); + /** + * Verifica se uma opção está setada. + * + * @param string $key + * + * @return bool + */ + protected function _hasOption($key) + { + return array_key_exists($key, $this->_options); } - return $this->_session; - } - /** - * Setter. - * @param CoreExt_Controller_Dispatcher_Interface $dispatcher - * @return CoreExt_Controller_Interface Provê interface fluída - */ - public function setDispatcher(CoreExt_Controller_Dispatcher_Interface $dispatcher) - { - $this->_dispatcher = $dispatcher; - return $this; - } + /** + * Retorna um valor de opção de configuração ou NULL caso a opção não esteja + * setada. + * + * @param string $key + * + * @return mixed|NULL + */ + public function getOption($key) + { + return $this->_hasOption($key) ? $this->_options[$key] : null; + } - /** - * Getter. - * @return CoreExt_Controller_Dispatcher_Interface - */ - public function getDispatcher() - { - if (is_null($this->_dispatcher)) { - require_once 'CoreExt/Controller/Dispatcher/Standard.php'; - $this->setDispatcher(new CoreExt_Controller_Dispatcher_Standard()); + /** + * Setter. + * + * @param CoreExt_Controller_Request_Interface $request + * + * @return CoreExt_Controller_Interface + */ + public function setRequest(CoreExt_Controller_Request_Interface $request) + { + $this->_request = $request; + + return $this; } - return $this->_dispatcher; - } - /** - * Redirect HTTP simples (espartaníssimo). - * - * Se a URL for relativa, prefixa o caminho com o baseurl configurado para - * o objeto CoreExt_Controller_Request. - * - * @param string $url - * @todo Implementar opções de configuração de código de status de - * redirecionamento. {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} - */ - public function redirect($url) - { - $parsed = parse_url($url, PHP_URL_HOST); + /** + * Getter para uma instância de CoreExt_Controller_Request_Interface. + * + * Instância via lazy initialization uma instância de + * CoreExt_Controller_Request_Interface caso nenhuma seja explicitamente + * atribuída a instância atual. + * + * @return CoreExt_Controller_Request_Interface + */ + public function getRequest() + { + if (is_null($this->_request)) { + require_once 'CoreExt/Controller/Request.php'; + $this->setRequest(new CoreExt_Controller_Request()); + } + + return $this->_request; + } - if ('' == $parsed['host']) { - $url = $this->getRequest()->getBaseurl() . '/' . $url; + /** + * Setter. + * + * @param CoreExt_Session_Abstract $session + * + * @return CoreExt_Controller_Interface + */ + public function setSession(CoreExt_Session_Abstract $session) + { + $this->_session = $session; + + return $this; } - header(sprintf('Location: %s', $url)); - } + /** + * Getter para uma instância de CoreExt_Session. + * + * Instância via lazy initialization uma instância de CoreExt_Session caso + * nenhuma seja explicitamente atribuída a instância atual. + * + * @return CoreExt_Session + */ + public function getSession() + { + if (is_null($this->_session)) { + require_once 'CoreExt/Session.php'; + $this->setSession(new CoreExt_Session()); + } + + return $this->_session; + } - /** - * Função de redirecionamento simples que leva em consideração - * o status code. - * - * @param string $url - * @param int $code - * - * @return void - */ - public function simpleRedirect(string $url, int $code = 302) - { - $codes = [ - 301 => 'HTTP/1.1 301 Moved Permanently', - 302 => 'HTTP/1.1 302 Found', - 303 => 'HTTP/1.1 303 See Other', - 304 => 'HTTP/1.1 304 Not Modified', - 305 => 'HTTP/1.1 305 Use Proxy' - ]; + /** + * Setter. + * + * @param CoreExt_Controller_Dispatcher_Interface $dispatcher + * + * @return CoreExt_Controller_Interface Provê interface fluída + */ + public function setDispatcher(CoreExt_Controller_Dispatcher_Interface $dispatcher) + { + $this->_dispatcher = $dispatcher; + + return $this; + } - if (empty($codes[$code])) { - $code = 302; + /** + * Getter. + * + * @return CoreExt_Controller_Dispatcher_Interface + */ + public function getDispatcher() + { + if (is_null($this->_dispatcher)) { + require_once 'CoreExt/Controller/Dispatcher/Standard.php'; + $this->setDispatcher(new CoreExt_Controller_Dispatcher_Standard()); + } + + return $this->_dispatcher; } - header($codes[$code]); - header('Location: ' . $url); + /** + * Redirect HTTP simples (espartaníssimo). + * + * Se a URL for relativa, prefixa o caminho com o baseurl configurado para + * o objeto CoreExt_Controller_Request. + * + * @param string $url + * + * @todo Implementar opções de configuração de código de status de + * redirecionamento. {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} + */ + public function redirect($url) + { + $parsed = parse_url($url, PHP_URL_HOST); + + if ('' == $parsed['host']) { + $url = $this->getRequest()->getBaseurl() . '/' . $url; + } + + header(sprintf('Location: %s', $url)); + } - die(); - } + /** + * Função de redirecionamento simples que leva em consideração + * o status code. + * + * @param string $url + * @param int $code + * + * @return void + */ + public function simpleRedirect(string $url, int $code = 302) + { + $codes = [ + 301 => 'HTTP/1.1 301 Moved Permanently', + 302 => 'HTTP/1.1 302 Found', + 303 => 'HTTP/1.1 303 See Other', + 304 => 'HTTP/1.1 304 Not Modified', + 305 => 'HTTP/1.1 305 Use Proxy' + ]; + + if (empty($codes[$code])) { + $code = 302; + } + + header($codes[$code]); + header('Location: ' . $url); + + die(); + } - /** - * Faz redirecionamento caso condição seja válida e encerra aplicação - * - * @param bool $condition - * @param string $url - * - * @return void - */ - public function redirectIf($condition, $url) - { - if ($condition) { - header('Location: ' . $url); - die(); + /** + * Faz redirecionamento caso condição seja válida e encerra aplicação + * + * @param bool $condition + * @param string $url + * + * @return void + */ + public function redirectIf($condition, $url) + { + if ($condition) { + header('Location: ' . $url); + die(); + } } - } } diff --git a/ieducar/lib/CoreExt/Controller/Dispatcher/Abstract.php b/ieducar/lib/CoreExt/Controller/Dispatcher/Abstract.php index ae69c6aea9..3da4e0338c 100644 --- a/ieducar/lib/CoreExt/Controller/Dispatcher/Abstract.php +++ b/ieducar/lib/CoreExt/Controller/Dispatcher/Abstract.php @@ -1,202 +1,169 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Controller/Dispatcher/Interface.php'; require_once 'CoreExt/Configurable.php'; -/** - * CoreExt_Controller_Dispatcher_Abstract abstract class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -abstract class CoreExt_Controller_Dispatcher_Abstract - implements CoreExt_Controller_Dispatcher_Interface, CoreExt_Configurable +abstract class CoreExt_Controller_Dispatcher_Abstract implements CoreExt_Controller_Dispatcher_Interface, CoreExt_Configurable { - /** - * Instância de CoreExt_Controller_Request_Interface - * @var CoreExt_Controller_Request_Interface - */ - protected $_request = NULL; - - /** - * Opções de configuração geral da classe. - * @var array - */ - protected $_options = array( - 'controller_default_name' => 'index', - 'action_default_name' => 'index' - ); - - /** - * @see CoreExt_Configurable#setOptions($options) - */ - public function setOptions(array $options = array()) - { - $defaultOptions = array_keys($this->getOptions()); - $passedOptions = array_keys($options); - - if (0 < count(array_diff($passedOptions, $defaultOptions))) { - throw new InvalidArgumentException( - sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) - ); + /** + * Instância de CoreExt_Controller_Request_Interface + * + * @var CoreExt_Controller_Request_Interface + */ + protected $_request = null; + + /** + * Opções de configuração geral da classe. + * + * @var array + */ + protected $_options = [ + 'controller_default_name' => 'index', + 'action_default_name' => 'index' + ]; + + /** + * @see CoreExt_Configurable#setOptions($options) + */ + public function setOptions(array $options = []) + { + $defaultOptions = array_keys($this->getOptions()); + $passedOptions = array_keys($options); + + if (0 < count(array_diff($passedOptions, $defaultOptions))) { + throw new InvalidArgumentException( + sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) + ); + } + + $this->_options = array_merge($this->getOptions(), $options); + + return $this; } - $this->_options = array_merge($this->getOptions(), $options); - return $this; - } - - /** - * @see CoreExt_Configurable#getOptions() - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Retorna um valor de opção de configuração ou NULL caso a opção não esteja - * setada. - * - * @param string $key - * @return mixed|NULL - */ - public function getOption($key) - { - return $this->_hasOption($key) ? $this->_options[$key] : NULL; - } - - /** - * Verifica se uma opção está setada. - * - * @param string $key - * @return bool - */ - protected function _hasOption($key) - { - return array_key_exists($key, $this->_options); - } - - /** - * @see CoreExt_Controller_Dispatcher_Interface#setRequest($request) - */ - public function setRequest(CoreExt_Controller_Request_Interface $request) - { - $this->_request = $request; - return $this; - } - - /** - * @see CoreExt_Controller_Dispatcher_Interface#getRequest() - */ - public function getRequest() - { - if (is_null($this->_request)) + /** + * @see CoreExt_Configurable#getOptions() + */ + public function getOptions() { - require_once 'CoreExt/Controller/Request.php'; - $this->setRequest(new CoreExt_Controller_Request()); + return $this->_options; } - return $this->_request; - } - - /** - * Retorna o componente 'path' de uma URL como array, onde cada item - * corresponde a um elemento do path. - * - * Exemplo: - * - * _getUrlPath()); - * // Array - * ( - * [0] => path1 - * [1] => path2 - * [2] => path3 - * ) - * - * - * @return array - */ - protected function _getUrlPath() - { - $path = parse_url($this->getRequest()->get('REQUEST_URI'), PHP_URL_PATH); - $path = explode('/', $path); - - $baseurl = parse_url($this->getRequest()->getBaseurl(), PHP_URL_PATH); - $baseurl = explode('/', $baseurl); - - $script = explode('/', $this->getRequest()->get('SCRIPT_FILENAME')); - $script = array_pop($script); - - // Retorna os elementos de path diferentes entre a REQUEST_URI e a baseurl - $path = array_diff_assoc($path, $baseurl); - - $items = count($path); - - if ($items >= 1) { - // Combina os elementos em um array cujo o índice começa do '0' - $path = array_combine(range(0, $items - 1), $path); - - // Caso o primeiro elemento seja o nome do script, remove-o - if (strtolower($script) === strtolower($path[0]) || '' === $path[0]) { - array_shift($path); - } + /** + * Retorna um valor de opção de configuração ou NULL caso a opção não esteja + * setada. + * + * @param string $key + * + * @return mixed|NULL + */ + public function getOption($key) + { + return $this->_hasOption($key) ? $this->_options[$key] : null; } - else { - $path = array(); + + /** + * Verifica se uma opção está setada. + * + * @param string $key + * + * @return bool + */ + protected function _hasOption($key) + { + return array_key_exists($key, $this->_options); } - return $path; - } - - /** - * @see CoreExt_Controller_Dispatcher_Interface#getController() - */ - public function getControllerName() - { - $path = $this->_getUrlPath(); - return isset($path[0]) ? $path[0] : $this->getOption('controller_default_name'); - } - - /** - * @see CoreExt_Controller_Dispatcher_Interface#getAction() - */ - public function getActionName() - { - $path = $this->_getUrlPath(); - return isset($path[1]) ? $path[1] : $this->getOption('action_default_name'); - } + /** + * @see CoreExt_Controller_Dispatcher_Interface#setRequest($request) + */ + public function setRequest(CoreExt_Controller_Request_Interface $request) + { + $this->_request = $request; + + return $this; + } + + /** + * @see CoreExt_Controller_Dispatcher_Interface#getRequest() + */ + public function getRequest() + { + if (is_null($this->_request)) { + require_once 'CoreExt/Controller/Request.php'; + $this->setRequest(new CoreExt_Controller_Request()); + } + + return $this->_request; + } + + /** + * Retorna o componente 'path' de uma URL como array, onde cada item + * corresponde a um elemento do path. + * + * Exemplo: + * + * _getUrlPath()); + * // Array + * ( + * [0] => path1 + * [1] => path2 + * [2] => path3 + * ) + * + * + * @return array + */ + protected function _getUrlPath() + { + $path = parse_url($this->getRequest()->get('REQUEST_URI'), PHP_URL_PATH); + $path = explode('/', $path); + + $baseurl = parse_url($this->getRequest()->getBaseurl(), PHP_URL_PATH); + $baseurl = explode('/', $baseurl); + + $script = explode('/', $this->getRequest()->get('SCRIPT_FILENAME')); + $script = array_pop($script); + + // Retorna os elementos de path diferentes entre a REQUEST_URI e a baseurl + $path = array_diff_assoc($path, $baseurl); + + $items = count($path); + + if ($items >= 1) { + // Combina os elementos em um array cujo o índice começa do '0' + $path = array_combine(range(0, $items - 1), $path); + + // Caso o primeiro elemento seja o nome do script, remove-o + if (strtolower($script) === strtolower($path[0]) || '' === $path[0]) { + array_shift($path); + } + } else { + $path = []; + } + + return $path; + } + + /** + * @see CoreExt_Controller_Dispatcher_Interface#getController() + */ + public function getControllerName() + { + $path = $this->_getUrlPath(); + + return isset($path[0]) ? $path[0] : $this->getOption('controller_default_name'); + } + + /** + * @see CoreExt_Controller_Dispatcher_Interface#getAction() + */ + public function getActionName() + { + $path = $this->_getUrlPath(); + + return isset($path[1]) ? $path[1] : $this->getOption('action_default_name'); + } } diff --git a/ieducar/lib/CoreExt/Controller/Dispatcher/Exception.php b/ieducar/lib/CoreExt/Controller/Dispatcher/Exception.php index da5e11b2b0..11a48a2237 100644 --- a/ieducar/lib/CoreExt/Controller/Dispatcher/Exception.php +++ b/ieducar/lib/CoreExt/Controller/Dispatcher/Exception.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Exception.php'; -/** - * CoreExt_Controller_Dispatcher_Exception class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Controller_Dispatcher_Exception extends CoreExt_Exception { } diff --git a/ieducar/lib/CoreExt/Controller/Dispatcher/Interface.php b/ieducar/lib/CoreExt/Controller/Dispatcher/Interface.php index 01b9aab1b6..a311fe997c 100644 --- a/ieducar/lib/CoreExt/Controller/Dispatcher/Interface.php +++ b/ieducar/lib/CoreExt/Controller/Dispatcher/Interface.php @@ -1,67 +1,34 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * CoreExt_Controller_Dispatcher_Interface interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Controller_Dispatcher_Interface { - /** - * Setter. - * @param CoreExt_Controller_Request_Interface $request - * @return CoreExt_Controller_Dispatcher_Interface Provê interface fluída - */ - public function setRequest(CoreExt_Controller_Request_Interface $request); + /** + * Setter. + * + * @param CoreExt_Controller_Request_Interface $request + * + * @return CoreExt_Controller_Dispatcher_Interface Provê interface fluída + */ + public function setRequest(CoreExt_Controller_Request_Interface $request); - /** - * Getter. - * @return CoreExt_Controller_Request_Interface - */ - public function getRequest(); + /** + * Getter. + * + * @return CoreExt_Controller_Request_Interface + */ + public function getRequest(); - /** - * Retorna uma string correspondendo a parte de controller de uma URL. - * @return string|NULL - */ - public function getControllerName(); + /** + * Retorna uma string correspondendo a parte de controller de uma URL. + * + * @return string|NULL + */ + public function getControllerName(); - /** - * Retorna uma string correspondendo a parte de action de uma URL. - * @return string|NULL - */ - public function getActionName(); + /** + * Retorna uma string correspondendo a parte de action de uma URL. + * + * @return string|NULL + */ + public function getActionName(); } diff --git a/ieducar/lib/CoreExt/Controller/Dispatcher/Standard.php b/ieducar/lib/CoreExt/Controller/Dispatcher/Standard.php index 5774a18136..dfd8dfcc3f 100644 --- a/ieducar/lib/CoreExt/Controller/Dispatcher/Standard.php +++ b/ieducar/lib/CoreExt/Controller/Dispatcher/Standard.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id: /ieducar/branches/teste/ieducar/lib/CoreExt/Controller/Dispatcher/Interface.php 645 2009-11-12T20:08:26.084511Z eriksen $ - */ - require_once 'CoreExt/Controller/Dispatcher/Abstract.php'; -/** - * CoreExt_Controller_Dispatcher_Standard class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Controller_Dispatcher_Standard extends CoreExt_Controller_Dispatcher_Abstract { } diff --git a/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/FrontStrategy.php b/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/FrontStrategy.php index 1a44d7da63..4c3ee4f020 100644 --- a/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/FrontStrategy.php +++ b/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/FrontStrategy.php @@ -1,89 +1,54 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Controller/Dispatcher/Abstract.php'; require_once 'CoreExt/Controller/Dispatcher/Strategy/Interface.php'; -/** - * CoreExt_Controller_Dispatcher_Strategy_FrontStrategy class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class CoreExt_Controller_Dispatcher_Strategy_FrontStrategy - extends CoreExt_Controller_Dispatcher_Abstract - implements CoreExt_Controller_Dispatcher_Strategy_Interface +class CoreExt_Controller_Dispatcher_Strategy_FrontStrategy extends CoreExt_Controller_Dispatcher_Abstract implements CoreExt_Controller_Dispatcher_Strategy_Interface { - /** - * Instância de CoreExt_Controller_Interface. - * @var CoreExt_Controller_Interface - */ - protected $_controller = NULL; + /** + * Instância de CoreExt_Controller_Interface. + * + * @var CoreExt_Controller_Interface + */ + protected $_controller = null; + + /** + * Construtor. + * + * @see CoreExt_Controller_Strategy_Interface#__construct($controller) + */ + public function __construct(CoreExt_Controller_Interface $controller) + { + $this->setController($controller); + } + + /** + * @see CoreExt_Controller_Strategy_Interface#setController($controller) + */ + public function setController(CoreExt_Controller_Interface $controller) + { + $this->_controller = $controller; - /** - * Construtor. - * @see CoreExt_Controller_Strategy_Interface#__construct($controller) - */ - public function __construct(CoreExt_Controller_Interface $controller) - { - $this->setController($controller); - } + return $this; + } - /** - * @see CoreExt_Controller_Strategy_Interface#setController($controller) - */ - public function setController(CoreExt_Controller_Interface $controller) - { - $this->_controller = $controller; - return $this; - } + /** + * @see CoreExt_Controller_Strategy_Interface#getController() + */ + public function getController() + { + return $this->_controller; + } - /** - * @see CoreExt_Controller_Strategy_Interface#getController() - */ - public function getController() - { - return $this->_controller; - } + /** + * Não implementado. + * + * @see CoreExt_Controller_Strategy_Interface#dispatch() + */ + public function dispatch() + { + require_once 'CoreExt/Controller/Dispatcher/Exception.php'; - /** - * Não implementado. - * @see CoreExt_Controller_Strategy_Interface#dispatch() - */ - public function dispatch() - { - require_once 'CoreExt/Controller/Dispatcher/Exception.php'; - throw new CoreExt_Controller_Dispatcher_Exception('Método CoreExt_Controller_Strategy_FrontStrategy::dispatch() não implementado.'); - } + throw new CoreExt_Controller_Dispatcher_Exception('Método CoreExt_Controller_Strategy_FrontStrategy::dispatch() não implementado.'); + } } diff --git a/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/Interface.php b/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/Interface.php index 201d8d7f88..12f730c69e 100644 --- a/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/Interface.php +++ b/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/Interface.php @@ -1,70 +1,37 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * CoreExt_Controller_Dispatcher_Strategy_Interface interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Controller_Dispatcher_Strategy_Interface { - /** - * Construtor. - * @param CoreExt_Controller_Interface $controller - */ - public function __construct(CoreExt_Controller_Interface $controller); + /** + * Construtor. + * + * @param CoreExt_Controller_Interface $controller + */ + public function __construct(CoreExt_Controller_Interface $controller); - /** - * Setter para a instância de CoreExt_Controller_Interface. - * @param CoreExt_Controller_Interface $controller - * @return CoreExt_Controller_Strategy_Interface Provê interface fluída - */ - public function setController(CoreExt_Controller_Interface $controller); + /** + * Setter para a instância de CoreExt_Controller_Interface. + * + * @param CoreExt_Controller_Interface $controller + * + * @return CoreExt_Controller_Strategy_Interface Provê interface fluída + */ + public function setController(CoreExt_Controller_Interface $controller); - /** - * Getter. - * @return CoreExt_Controller_Interface - */ - public function getController(); + /** + * Getter. + * + * @return CoreExt_Controller_Interface + */ + public function getController(); - /** - * Realiza o dispatch da requisição, encaminhando o controle da execução ao - * controller adequado. - * - * @return bool - * @throws Exception - */ - public function dispatch(); + /** + * Realiza o dispatch da requisição, encaminhando o controle da execução ao + * controller adequado. + * + * @return bool + * + * @throws Exception + */ + public function dispatch(); } diff --git a/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/PageStrategy.php b/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/PageStrategy.php index 0ba91c5478..2777fedd4d 100644 --- a/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/PageStrategy.php +++ b/ieducar/lib/CoreExt/Controller/Dispatcher/Strategy/PageStrategy.php @@ -1,73 +1,42 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Controller/Dispatcher/Abstract.php'; require_once 'CoreExt/Controller/Dispatcher/Strategy/Interface.php'; -/** - * CoreExt_Controller_Strategy_PageStrategy class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class CoreExt_Controller_Dispatcher_Strategy_PageStrategy extends CoreExt_Controller_Dispatcher_Abstract implements CoreExt_Controller_Dispatcher_Strategy_Interface { +class CoreExt_Controller_Dispatcher_Strategy_PageStrategy extends CoreExt_Controller_Dispatcher_Abstract implements CoreExt_Controller_Dispatcher_Strategy_Interface +{ /** * Instância de CoreExt_Controller_Interface. + * * @var CoreExt_Controller_Interface */ - protected $_controller = NULL; + protected $_controller = null; /** * Construtor. + * * @see CoreExt_Controller_Strategy_Interface#__construct($controller) */ - public function __construct(CoreExt_Controller_Interface $controller) { + public function __construct(CoreExt_Controller_Interface $controller) + { $this->setController($controller); } /** * @see CoreExt_Controller_Strategy_Interface#setController($controller) */ - public function setController(CoreExt_Controller_Interface $controller) { + public function setController(CoreExt_Controller_Interface $controller) + { $this->_controller = $controller; + return $this; } /** * @see CoreExt_Controller_Strategy_Interface#getController() */ - public function getController() { + public function getController() + { return $this->_controller; } @@ -96,13 +65,18 @@ public function getController() { * * * @global DS Constante para DIRECTORY_SEPARATOR + * * @see CoreExt_Controller_Strategy_Interface#dispatch() + * * @todo Funções de controle de buffer não funcionam por conta de chamadas * a die() e exit() nas classes clsDetalhe, clsCadastro e clsListagem. + * * @throws CoreExt_Exception_FileNotFoundException + * * @return bool */ - public function dispatch() { + public function dispatch() + { if (extension_loaded('newrelic')) { newrelic_name_transaction($_SERVER['REDIRECT_URL']); } @@ -115,7 +89,7 @@ public function dispatch() { $controllerDir = $this->getController()->getOption('controller_dir'); $controllerType = $this->getController()->getOption('controller_type'); - $controllerFile = array($basepath, $controller, $controllerDir, $pageController); + $controllerFile = [$basepath, $controller, $controllerDir, $pageController]; $controllerFile = sprintf('%s.php', implode(DS, $controllerFile)); if (!file_exists($controllerFile)) { @@ -137,6 +111,6 @@ public function dispatch() { $this->getController()->getView()->setContents(ob_get_contents()); ob_end_clean(); - return TRUE; + return true; } } diff --git a/ieducar/lib/CoreExt/Controller/Front.php b/ieducar/lib/CoreExt/Controller/Front.php index 36576d43e3..08379da846 100644 --- a/ieducar/lib/CoreExt/Controller/Front.php +++ b/ieducar/lib/CoreExt/Controller/Front.php @@ -1,225 +1,177 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Controller/Abstract.php'; -/** - * CoreExt_Controller_Front class. - * - * Essa é uma implementação simples do design pattern {@link http://martinfowler.com/eaaCatalog/frontController.html front controller}, - * que tem como objetivo manusear e encaminhar a requisição para uma classe - * que se responsabilize pelo processamento do recurso solicitado. - * - * Apesar de ser um front controller, o encaminhamento para uma classe - * {@link http://en.wikipedia.org/wiki/Command_pattern command} não está - * implementado. - * - * Entretanto, está disponível o encaminhamento para uma classe que implemente - * o pattern {@link http://martinfowler.com/eaaCatalog/pageController.html page controller}, - * ou seja, qualquer classe que implemente a interface - * CoreExt_Controller_Page_Interface. - * - * O processo de encaminhamento (dispatching), é definido por uma classe - * {@link http://en.wikipedia.org/wiki/Strategy_pattern strategy}. - * - * Algumas opções afetam o comportamento dessa classe. As opções disponíveis - * para configurar uma instância da classe são: - * - basepath: diretório em que os implementadores de command e page controller - * serão procurados - * - controller_dir: determina o nome do diretório em que os controllers deverão - * estar salvos - * - controller_type: tipo de controller a ser instanciado. Uma instância de - * CoreExt_Controller_Front pode usar apenas um tipo por processo de - * dispatch() e o valor dessa opção determina qual strategy de dispatch será - * utilizada (CoreExt_Controller_Strategy). - * - * Por padrão, os valores de controller_dir e controller_type são definidos para - * 'Views' e 2, respectivamente. Isso significa que a estratégia de page - * controller será utilizada durante a chamada ao método dispatch(). - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Controller_Front extends CoreExt_Controller_Abstract { - /** - * Opções para definição de qual tipo de controller utilizar durante a - * execução de dispatch(). - * @var int - */ - const CONTROLLER_FRONT = 1; - const CONTROLLER_PAGE = 2; - - /** - * A instância singleton de CoreExt_Controller_Interface. - * @var CoreExt_Controller_Interface|NULL - */ - protected static $_instance = NULL; - - /** - * Opções de configuração geral da classe. - * @var array - */ - protected $_options = array( - 'basepath' => NULL, - 'controller_type' => self::CONTROLLER_PAGE, - 'controller_dir' => 'Views' - ); - - /** - * Contém os valores padrão da configuração. - * @var array - */ - protected $_defaultOptions = array(); - - /** - * Uma instância de CoreExt_View_Abstract - * @var CoreExt_View_Abstract - */ - protected $_view = NULL; - - /** - * Construtor singleton. - */ - protected function __construct() - { - $this->_defaultOptions = $this->getOptions(); - } - - /** - * Retorna a instância singleton. - * @return CoreExt_Controller_Front - */ - public static function getInstance() - { - if (is_null(self::$_instance)) { - self::$_instance = new self(); + /** + * Opções para definição de qual tipo de controller utilizar durante a + * execução de dispatch(). + * + * @var int + */ + const CONTROLLER_FRONT = 1; + const CONTROLLER_PAGE = 2; + + /** + * A instância singleton de CoreExt_Controller_Interface. + * + * @var CoreExt_Controller_Interface|NULL + */ + protected static $_instance = null; + + /** + * Opções de configuração geral da classe. + * + * @var array + */ + protected $_options = [ + 'basepath' => null, + 'controller_type' => self::CONTROLLER_PAGE, + 'controller_dir' => 'Views' + ]; + + /** + * Contém os valores padrão da configuração. + * + * @var array + */ + protected $_defaultOptions = []; + + /** + * Uma instância de CoreExt_View_Abstract + * + * @var CoreExt_View_Abstract + */ + protected $_view = null; + + /** + * Construtor singleton. + */ + protected function __construct() + { + $this->_defaultOptions = $this->getOptions(); + } + + /** + * Retorna a instância singleton. + * + * @return CoreExt_Controller_Front + */ + public static function getInstance() + { + if (is_null(self::$_instance)) { + self::$_instance = new self(); + } + + return self::$_instance; + } + + /** + * Recupera os valores de configuração original da instância. + * + * @return CoreExt_Configurable Provê interface fluída + */ + public function resetOptions() + { + $this->setOptions($this->_defaultOptions); + + return $this; } - return self::$_instance; - } - - /** - * Recupera os valores de configuração original da instância. - * @return CoreExt_Configurable Provê interface fluída - */ - public function resetOptions() - { - $this->setOptions($this->_defaultOptions); - return $this; - } - - /** - * Encaminha a execução para o objeto CoreExt_Dispatcher_Interface apropriado. - * @return CoreExt_Controller_Interface Provê interface fluída - * @see CoreExt_Controller_Interface#dispatch() - */ - public function dispatch() - { - $this->_getControllerStrategy()->dispatch(); - return $this; - } - - /** - * Retorna o conteúdo gerado pelo controller. - * @return string - */ - public function getViewContents() - { - return $this->getView()->getContents(); - } - - /** - * Setter. - * @param CoreExt_View_Abstract $view - * @return CoreExt_Controller_Interface Provê interface fluída - */ - public function setView(CoreExt_View_Abstract $view) - { - $this->_view = $view; - return $this; - } - - /** - * Getter para uma instância de CoreExt_View_Abstract. - * - * Instância via lazy initialization uma instância de CoreExt_View caso - * nenhuma seja explicitamente atribuída a instância atual. - * - * @return CoreExt_View_Abstract - */ - public function getView() - { - if (is_null($this->_view)) { - require_once 'CoreExt/View.php'; - $this->setView(new CoreExt_View()); + + /** + * Encaminha a execução para o objeto CoreExt_Dispatcher_Interface apropriado. + * + * @return CoreExt_Controller_Interface Provê interface fluída + * + * @see CoreExt_Controller_Interface#dispatch() + */ + public function dispatch() + { + $this->_getControllerStrategy()->dispatch(); + + return $this; } - return $this->_view; - } - - /** - * Getter para uma instância de CoreExt_Controller_Dispatcher_Interface. - * - * Instância via lazy initialization uma instância de - * CoreExt_Controller_Dispatcher caso nenhuma seja explicitamente - * atribuída a instância atual. - * - * @return CoreExt_Controller_Dispatcher_Interface - */ - public function getDispatcher() - { - if (is_null($this->_dispatcher)) { - $this->setDispatcher($this->_getControllerStrategy()); + + /** + * Retorna o conteúdo gerado pelo controller. + * + * @return string + */ + public function getViewContents() + { + return $this->getView()->getContents(); } - return $this->_dispatcher; - } - - /** - * Getter para a estratégia de controller, definida em runtime. - * @return CoreExt_Controller_Strategy - */ - protected function _getControllerStrategy() - { - switch($this->getOption('controller_type')) { - case 1: - require_once 'CoreExt/Controller/Dispatcher/Strategy/FrontStrategy.php'; - $strategy = 'CoreExt_Controller_Dispatcher_Strategy_FrontStrategy'; - break; - case 2: - require_once 'CoreExt/Controller/Dispatcher/Strategy/PageStrategy.php'; - $strategy = 'CoreExt_Controller_Dispatcher_Strategy_PageStrategy'; - break; + + /** + * Setter. + * + * @param CoreExt_View_Abstract $view + * + * @return CoreExt_Controller_Interface Provê interface fluída + */ + public function setView(CoreExt_View_Abstract $view) + { + $this->_view = $view; + + return $this; + } + + /** + * Getter para uma instância de CoreExt_View_Abstract. + * + * Instância via lazy initialization uma instância de CoreExt_View caso + * nenhuma seja explicitamente atribuída a instância atual. + * + * @return CoreExt_View_Abstract + */ + public function getView() + { + if (is_null($this->_view)) { + require_once 'CoreExt/View.php'; + $this->setView(new CoreExt_View()); + } + + return $this->_view; + } + + /** + * Getter para uma instância de CoreExt_Controller_Dispatcher_Interface. + * + * Instância via lazy initialization uma instância de + * CoreExt_Controller_Dispatcher caso nenhuma seja explicitamente + * atribuída a instância atual. + * + * @return CoreExt_Controller_Dispatcher_Interface + */ + public function getDispatcher() + { + if (is_null($this->_dispatcher)) { + $this->setDispatcher($this->_getControllerStrategy()); + } + + return $this->_dispatcher; + } + + /** + * Getter para a estratégia de controller, definida em runtime. + * + * @return CoreExt_Controller_Strategy + */ + protected function _getControllerStrategy() + { + switch ($this->getOption('controller_type')) { + case 1: + require_once 'CoreExt/Controller/Dispatcher/Strategy/FrontStrategy.php'; + $strategy = 'CoreExt_Controller_Dispatcher_Strategy_FrontStrategy'; + break; + + case 2: + require_once 'CoreExt/Controller/Dispatcher/Strategy/PageStrategy.php'; + $strategy = 'CoreExt_Controller_Dispatcher_Strategy_PageStrategy'; + break; + } + + return new $strategy($this); } - return new $strategy($this); - } } diff --git a/ieducar/lib/CoreExt/Controller/Interface.php b/ieducar/lib/CoreExt/Controller/Interface.php index edf8fe1e74..38c20c2bfb 100644 --- a/ieducar/lib/CoreExt/Controller/Interface.php +++ b/ieducar/lib/CoreExt/Controller/Interface.php @@ -1,50 +1,12 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Configurable.php'; -/** - * CoreExt_Controller_Interface interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Controller_Interface extends CoreExt_Configurable { - /** - * Despacha o controle da execução para uma instância de - * CoreExt_Controller_Interface. - */ - public function dispatch(); + /** + * Despacha o controle da execução para uma instância de + * CoreExt_Controller_Interface. + */ + public function dispatch(); } diff --git a/ieducar/lib/CoreExt/Controller/Page.php b/ieducar/lib/CoreExt/Controller/Page.php index e3b6aa50ad..1405107dbc 100644 --- a/ieducar/lib/CoreExt/Controller/Page.php +++ b/ieducar/lib/CoreExt/Controller/Page.php @@ -1,43 +1,5 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * CoreExt_Controller_Page abstract class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ abstract class CoreExt_Controller_Page implements CoreExt_Controller_Page_Interface { } diff --git a/ieducar/lib/CoreExt/Controller/Page/Interface.php b/ieducar/lib/CoreExt/Controller/Page/Interface.php index d7a0f72f7b..900fe56aea 100644 --- a/ieducar/lib/CoreExt/Controller/Page/Interface.php +++ b/ieducar/lib/CoreExt/Controller/Page/Interface.php @@ -1,51 +1,15 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Controller/Interface.php'; -/** - * CoreExt_Controller_Page_Interface interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Controller_Page_Interface extends CoreExt_Controller_Interface { - /** - * Gera o código HTML para a requisição. - * @param CoreExt_Controller_Page_Interface $instance - * @return string - */ - public function generate(CoreExt_Controller_Page_Interface $instance); + /** + * Gera o código HTML para a requisição. + * + * @param CoreExt_Controller_Page_Interface $instance + * + * @return string + */ + public function generate(CoreExt_Controller_Page_Interface $instance); } diff --git a/ieducar/lib/CoreExt/Controller/Request.php b/ieducar/lib/CoreExt/Controller/Request.php index cfee4f5691..ce85f17f02 100644 --- a/ieducar/lib/CoreExt/Controller/Request.php +++ b/ieducar/lib/CoreExt/Controller/Request.php @@ -31,7 +31,7 @@ public function __construct(array $options = []) public function setOptions(array $options = []) { $defaultOptions = array_keys($this->getOptions()); - $passedOptions = array_keys($options); + $passedOptions = array_keys($options); if (0 < count(array_diff($passedOptions, $defaultOptions))) { throw new InvalidArgumentException( @@ -101,14 +101,19 @@ public function get($key) switch (true) { case isset($this->_data[$key]): return $this->_data[$key]; + case isset($_GET[$key]): return $_GET[$key]; + case isset($_POST[$key]): return $_POST[$key]; + case isset($_COOKIE[$key]): return $_COOKIE[$key]; + case isset($_SERVER[$key]): return $_SERVER[$key]; + default: break; } diff --git a/ieducar/lib/CoreExt/Controller/Request/Interface.php b/ieducar/lib/CoreExt/Controller/Request/Interface.php index 59cb49ba50..4a059d56a3 100644 --- a/ieducar/lib/CoreExt/Controller/Request/Interface.php +++ b/ieducar/lib/CoreExt/Controller/Request/Interface.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Configurable.php'; -/** - * CoreExt_Controller_Request_Interface interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Controller - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Controller_Request_Interface extends CoreExt_Configurable { } diff --git a/ieducar/lib/CoreExt/DataMapper.php b/ieducar/lib/CoreExt/DataMapper.php index 40ec9b2616..67d58f87f6 100644 --- a/ieducar/lib/CoreExt/DataMapper.php +++ b/ieducar/lib/CoreExt/DataMapper.php @@ -1,811 +1,864 @@ - * @category i-Educar - * @license @@license@@ - * @package CoreExt_DataMapper - * @since Classe disponível desde a versão 1.1.0 - * @todo Refactoring dos métodos get*Statment() com extract method - * @todo Testes para ordenação em findAll() - * @version @@package_version@@ - */ + abstract class CoreExt_DataMapper { - /** - * Classe CoreExt_Entity para este data mapper. - * @var string - */ - protected $_entityClass = ''; - - /** - * Mapeamento objeto-relacional, atributos-campos. - * @var array - */ - protected $_attributeMap = array(); - - /** - * Atributos não-persistíveis. - * @var array - */ - protected $_notPersistable = array(); - - /** - * Define as chaves primárias da tabela. Configurada automaticamente para - * usar o campo identidade de CoreExt_Entity. - * @see CoreExt_Entity::_createIdentityField() - * @var array - */ - protected $_primaryKey = array('id' => 'id'); - - /** - * Objeto de conexão com o banco de dados. - * @var clsBanco - */ - protected $_dbAdapter = NULL; - - /** - * Instância padrão para uso em objetos CoreExt_DataMapper. Isso possibilita - * que a mesma instância do adapter de conexão com o banco de dados seja - * reutilizado em várias instâncias de CoreExt_DataMapper. - * - * @var clsBanco - */ - protected static $_defaultDbAdapter = NULL; - - /** - * Nome da tabela em que o objeto é mapeado. - * @var string - */ - protected $_tableName = ''; - - /** - * Nome do schema da tabela. - * @var string - */ - protected $_tableSchema = ''; - - /** - * @var CoreExt_Locale - */ - protected $_locale = NULL; - - /** - * Construtor. - * @param clsBanco $db - */ - public function __construct(clsBanco $db = NULL) - { - if (!is_null($db)) { - $this->_setDbAdapter($db); - } - } - - /** - * Setter para configuração de um adapter de banco de dados padrão usado - * nas instâncias concretas de CoreExt_DataMapper quando nenhuma instância de - * clsBanco é passada ao construtor. - * @param clsBanco $db - */ - public static function setDefaultDbAdapter(clsBanco $db = NULL) - { - self::$_defaultDbAdapter = $db; - } - - /** - * Reseta o adapter padrão, fazendo com que CoreExt_DataMapper instancie - * automaticamente uma instância de clsBanco quando necessário. - */ - public static function resetDefaultDbAdapter() - { - self::setDefaultDbAdapter(NULL); - } - - /** - * Setter para o objeto de adapter responsável pela interação com o banco de - * dados. - * - * @param clsBanco $db - * @return CoreExt_DataMapper Provê interface fluída - */ - protected function _setDbAdapter(clsBanco $db) - { - $this->_dbAdapter = $db; - return $this; - } - - /** - * Getter para o objeto de adapter de banco de dados. - * - * Se nenhuma instância foi explicitamente passada ao construtor, - * tenta atribuir uma instância por padrão, na seguinte ordem: - * - * - Usando o adapter provido pelo método estático setDefaultDbAdapter - * (útil para usar várias instâncias de CoreExt_DataMapper sem a instanciação - * da classe clsBanco) - * - Ou, instanciando a classe clsBanco - * - * Usar o setter estático tem a vantagem de reduzir o overhead causado pela - * instanciação a clsBanco a cada novo objeto CoreExt_DataMapper. - * - * @return clsBanco - */ - protected function _getDbAdapter() - { - if (is_null($this->_dbAdapter)) { - if (!is_null(self::$_defaultDbAdapter)) { - $adapter = self::$_defaultDbAdapter; - } - else { - $adapter = new clsBanco(array('fetchMode' => clsBanco::FETCH_ASSOC)); - } - $this->_setDbAdapter($adapter); - } - return $this->_dbAdapter; - } - - /** - * Getter público para o objeto de adapter de banco de dados. - * @return clsBanco - */ - public function getDbAdapter() - { - return $this->_getDbAdapter(); - } - - /** - * Retorna o nome da tabela. Se o $_tableSchema for informado, retorna o - * nome da tabela no formato 'schema.table'. - * - * @return string - */ - protected function _getTableName() - { - return $this->_tableSchema != '' ? - $this->_tableSchema . '.' . $this->_tableName : $this->_tableName; - } - - /** - * Retorna o nome do recurso, isto é o nome da tabela sem '_', - * Ex: transporte_aluno => transporte aluno. - * - * @return string - */ - public function resourceName() - { - return strtolower(str_replace('_', ' ', $this->_tableName)); - } - - /** - * Retorna os nomes das colunas da tabela em um array, de acordo com o array - * de dados associativo $data. - * - * Caso nenhum array seja passado, é usado o array de atributos da classe - * CoreExt_Entity ao qual o data mapper mapeia. - * - * @param array $data - * @return array - */ - protected function _getTableColumnsArray(array $data = array()) - { - $columns = array(); - - if (0 == count($data)) { - $tempEntity = new $this->_entityClass(); - $data = $tempEntity->toDataArray(); - } + /** + * Classe CoreExt_Entity para este data mapper. + * + * @var string + */ + protected $_entityClass = ''; + + /** + * Mapeamento objeto-relacional, atributos-campos. + * + * @var array + */ + protected $_attributeMap = []; + + /** + * Atributos não-persistíveis. + * + * @var array + */ + protected $_notPersistable = []; - $tempColumns = array_map(array($this, '_getTableColumn'), array_keys($data)); + /** + * Define as chaves primárias da tabela. Configurada automaticamente para + * usar o campo identidade de CoreExt_Entity. + * + * @see CoreExt_Entity::_createIdentityField() + * + * @var array + */ + protected $_primaryKey = ['id' => 'id']; - // Remove colunas não-persistíveis - foreach ($tempColumns as $key => $column) { - if (is_null($column)) { - continue; - } - $columns[] = $column; + /** + * Objeto de conexão com o banco de dados. + * + * @var clsBanco + */ + protected $_dbAdapter = null; + + /** + * Instância padrão para uso em objetos CoreExt_DataMapper. Isso possibilita + * que a mesma instância do adapter de conexão com o banco de dados seja + * reutilizado em várias instâncias de CoreExt_DataMapper. + * + * @var clsBanco + */ + protected static $_defaultDbAdapter = null; + + /** + * Nome da tabela em que o objeto é mapeado. + * + * @var string + */ + protected $_tableName = ''; + + /** + * Nome do schema da tabela. + * + * @var string + */ + protected $_tableSchema = ''; + + /** + * @var CoreExt_Locale + */ + protected $_locale = null; + + /** + * Construtor. + * + * @param clsBanco $db + */ + public function __construct(clsBanco $db = null) + { + if (!is_null($db)) { + $this->_setDbAdapter($db); + } } - return $columns; - } - - /** - * Retorna o nome do campo da tabela caso o identificador do atributo - * esteja mapeado em $_attributeMap. - * - * Caso contrário, retorna o próprio identificador do atributo. - * - * @param string $key - * @return string|NULL NULL para coluna não persistível - */ - protected function _getTableColumn($key) - { - if (in_array($key, $this->_notPersistable)) { - return NULL; + /** + * Setter para configuração de um adapter de banco de dados padrão usado + * nas instâncias concretas de CoreExt_DataMapper quando nenhuma instância de + * clsBanco é passada ao construtor. + * + * @param clsBanco $db + */ + public static function setDefaultDbAdapter(clsBanco $db = null) + { + self::$_defaultDbAdapter = $db; } - if (array_key_exists($key, $this->_attributeMap)) { - return $this->_attributeMap[$key]; + /** + * Reseta o adapter padrão, fazendo com que CoreExt_DataMapper instancie + * automaticamente uma instância de clsBanco quando necessário. + */ + public static function resetDefaultDbAdapter() + { + self::setDefaultDbAdapter(null); } - return $key; - } - - /** - * Retorna os nomes das colunas da tabela separados por vírgula e espaço (', '). - * - * @param array $data - * @return string - */ - protected function _getTableColumns(array $data = array()) - { - return join(', ', $this->_getTableColumnsArray($data)); - } - - /** - * Retorna uma query SQL de recuperação de todos os registros de uma tabela. - * - * @param array $data - * @param array $where - * @param array $orderBy - * @return string - */ - protected function _getFindAllStatment(array $data = array(), array $where = array(), - array $orderBy = array()) - { - $whereArg = $where; - $where = array(); - $order = array(); - - if (0 < count($whereArg)) { - foreach ($whereArg as $key => $value) { - // Caso $key seja um inteiro ela não representa uma coluna, e apenas nos importamos com o where - if (is_integer($key)) { - $where[] = sprintf('%s', $value); - continue; - } - $whereName = $this->_getTableColumn($key); - - preg_match('/[<,=,>]/', $value, $matches); - $hasComparisonSign = ! empty($matches); - - // Caso $value contenha <, > ou =, ex: '> $1', não adiciona sinal de igual. - if ($hasComparisonSign) - $where[] = sprintf("%s %s", $whereName, $value); - - // Caso $value contenha parametros para consulta preparada ($1, $2...), não adiciona $value entre aspas. - elseif (strpos($value, '$') > -1) - $where[] = sprintf("%s = %s", $whereName, $value); - - else - $where[] = sprintf("%s = '%s'", $whereName, $value); - } + + /** + * Setter para o objeto de adapter responsável pela interação com o banco de + * dados. + * + * @param clsBanco $db + * + * @return CoreExt_DataMapper Provê interface fluída + */ + protected function _setDbAdapter(clsBanco $db) + { + $this->_dbAdapter = $db; + + return $this; } - else { - $where[] = '1 = 1'; + + /** + * Getter para o objeto de adapter de banco de dados. + * + * Se nenhuma instância foi explicitamente passada ao construtor, + * tenta atribuir uma instância por padrão, na seguinte ordem: + * + * - Usando o adapter provido pelo método estático setDefaultDbAdapter + * (útil para usar várias instâncias de CoreExt_DataMapper sem a instanciação + * da classe clsBanco) + * - Ou, instanciando a classe clsBanco + * + * Usar o setter estático tem a vantagem de reduzir o overhead causado pela + * instanciação a clsBanco a cada novo objeto CoreExt_DataMapper. + * + * @return clsBanco + */ + protected function _getDbAdapter() + { + if (is_null($this->_dbAdapter)) { + if (!is_null(self::$_defaultDbAdapter)) { + $adapter = self::$_defaultDbAdapter; + } else { + $adapter = new clsBanco(['fetchMode' => clsBanco::FETCH_ASSOC]); + } + $this->_setDbAdapter($adapter); + } + + return $this->_dbAdapter; } - if (0 < count($orderBy)) { - foreach ($orderBy as $key => $value) { - $order[] = sprintf('%s %s', $this->_getTableColumn($key), $value); - } - $order = sprintf('ORDER BY %s', implode(',', $order)); + /** + * Getter público para o objeto de adapter de banco de dados. + * + * @return clsBanco + */ + public function getDbAdapter() + { + return $this->_getDbAdapter(); } - else { - $order = ''; + + /** + * Retorna o nome da tabela. Se o $_tableSchema for informado, retorna o + * nome da tabela no formato 'schema.table'. + * + * @return string + */ + protected function _getTableName() + { + return $this->_tableSchema != '' ? + $this->_tableSchema . '.' . $this->_tableName : $this->_tableName; } - return sprintf("SELECT %s FROM %s WHERE %s %s", $this->_getTableColumns($data), - $this->_getTableName(), implode(' AND ', $where), $order); - } - - /** - * Retorna uma query SQL de recuperação de registro baseada na identidade. - * - * Converte o argumento $pkey para float, como forma de - * evitar os problemas do tipo int em ambientes 32 bit (mais especificamente, - * a ausência de um tipo long). - * - * @link http://php.net/manual/en/language.types.integer.php - * @link http://php.net/manual/en/function.intval.php - * @param array|long $pkey - * @return string - */ - protected function _getFindStatment($pkey) - { - $where = array(); - - if (!is_array($pkey)){ - $keys = array_keys($this->_primaryKey); - $pkey = array( - array_shift($keys) => $pkey - ); - } - - foreach ($pkey as $key => $pk) { - $whereName = $this->_getTableColumn($key); - $where[] = sprintf("%s = '%s'", $whereName, $pk); + /** + * Retorna o nome do recurso, isto é o nome da tabela sem '_', + * Ex: transporte_aluno => transporte aluno. + * + * @return string + */ + public function resourceName() + { + return strtolower(str_replace('_', ' ', $this->_tableName)); } - return sprintf("SELECT %s FROM %s WHERE %s", $this->_getTableColumns(), - $this->_getTableName(), implode(' AND ', $where)); - } - - /** - * Retorna uma query SQL para a operação INSERT. Utiliza para isso os - * atributos da instância CoreExt_Entity, com o cuidado de remover o - * campo identidade. - * - * Uma query gerada por esse método segue a forma: - * - * INSERT INTO [schema.]table (column) VALUES ('value'); - * - * - * @param CoreExt_Entity $instance - * @return string - */ - protected function _getSaveStatment(CoreExt_Entity $instance) - { - $sql = 'INSERT INTO %s (%s) VALUES (%s)'; - - //Remove campos null - $data = $this->_cleanNullValuesToSave($instance); - - // Pega apenas os valores do array - $values = array_values($data); - - // Colunas para formar a query - $columns = $this->_getTableColumns($data); - - // Trata os valores NULL diferentemente dos outros, para evitar erro - // de execução query - $valuesStmt = array(); - for ($i = 0, $count = count($values); $i < $count; $i++) { - $value = $values[$i]; - $valuesStmt[] = sprintf("'%s'", pg_escape_string($value)); + /** + * Retorna os nomes das colunas da tabela em um array, de acordo com o array + * de dados associativo $data. + * + * Caso nenhum array seja passado, é usado o array de atributos da classe + * CoreExt_Entity ao qual o data mapper mapeia. + * + * @param array $data + * + * @return array + */ + protected function _getTableColumnsArray(array $data = []) + { + $columns = []; + + if (0 == count($data)) { + $tempEntity = new $this->_entityClass(); + $data = $tempEntity->toDataArray(); + } + + $tempColumns = array_map([$this, '_getTableColumn'], array_keys($data)); + + // Remove colunas não-persistíveis + foreach ($tempColumns as $key => $column) { + if (is_null($column)) { + continue; + } + $columns[] = $column; + } + + return $columns; } - $valuesStmt = join(", ", $valuesStmt); - return sprintf($sql, $this->_getTableName(), $columns, $valuesStmt); - } - - /** - * Retorna uma query SQL para a operação UPDATE. Utiliza para isso os - * atributos da instância CoreExt_Entity, usando o atributo identidade - * para especificar qual registro atualizar na tabela. - * - * Uma query gerada por esse método segue a forma: - * - * UPDATE [schema.]table SET column='value' WHERE id = 'idValue'; - * - * - * @param CoreExt_Entity $instance - * @return string - */ - protected function _getUpdateStatment(CoreExt_Entity $instance) - { - $sql = 'UPDATE %s SET %s WHERE %s'; - // Convert a entity em array, traz o array com dados formatados - $data = $this->_getDbAdapter()->formatValues($instance->toDataArray()); - - // Remove o campo identidade e campos não-persistentes - $data = $this->_cleanData($data); - if (empty($data)) { - return ''; + /** + * Retorna o nome do campo da tabela caso o identificador do atributo + * esteja mapeado em $_attributeMap. + * + * Caso contrário, retorna o próprio identificador do atributo. + * + * @param string $key + * + * @return string|NULL NULL para coluna não persistível + */ + protected function _getTableColumn($key) + { + if (in_array($key, $this->_notPersistable)) { + return null; + } + + if (array_key_exists($key, $this->_attributeMap)) { + return $this->_attributeMap[$key]; + } + + return $key; } - // Trata os valores NULL diferentemente dos outros, para evitar erro - // de execução query - $columns = array(); - foreach ($data as $key => $value) { - $columnName = $this->_getTableColumn($key); - $replaceString = "%s = '%s'"; - - if (is_null($value) || (0 == $value && $instance->_isReferenceDataMapper($key)) - ) { - $value = "NULL"; - $replaceString = "%s = %s"; - } - - $columns[] = sprintf($replaceString, $columnName, pg_escape_string($value)); + + /** + * Retorna os nomes das colunas da tabela separados por vírgula e espaço (', '). + * + * @param array $data + * + * @return string + */ + protected function _getTableColumns(array $data = []) + { + return join(', ', $this->_getTableColumnsArray($data)); } - $where = array(); - $keyToUpdate = $this->buildKeyToFind($instance); - foreach ($keyToUpdate as $key => $value) { - $whereName = $this->_getTableColumn($key); - $where[] = sprintf("%s = '%s'", $whereName, $value); + /** + * Retorna uma query SQL de recuperação de todos os registros de uma tabela. + * + * @param array $data + * @param array $where + * @param array $orderBy + * + * @return string + */ + protected function _getFindAllStatment( + array $data = [], + array $where = [], + array $orderBy = [] + ) { + $whereArg = $where; + $where = []; + $order = []; + + if (0 < count($whereArg)) { + foreach ($whereArg as $key => $value) { + // Caso $key seja um inteiro ela não representa uma coluna, e apenas nos importamos com o where + if (is_integer($key)) { + $where[] = sprintf('%s', $value); + continue; + } + + $whereName = $this->_getTableColumn($key); + + preg_match('/[<,=,>]/', $value, $matches); + + $hasComparisonSign = !empty($matches); + + // Caso $value contenha <, > ou =, ex: '> $1', não adiciona sinal de igual. + if ($hasComparisonSign) { + $where[] = sprintf('%s %s', $whereName, $value); + } // Caso $value contenha parametros para consulta preparada ($1, $2...), não adiciona $value entre aspas. + elseif (strpos($value, '$') > -1) { + $where[] = sprintf('%s = %s', $whereName, $value); + } else { + $where[] = sprintf('%s = \'%s\'', $whereName, $value); + } + } + } else { + $where[] = '1 = 1'; + } + + if (0 < count($orderBy)) { + foreach ($orderBy as $key => $value) { + $order[] = sprintf('%s %s', $this->_getTableColumn($key), $value); + } + + $order = sprintf('ORDER BY %s', implode(',', $order)); + } else { + $order = ''; + } + + return sprintf( + 'SELECT %s FROM %s WHERE %s %s', + $this->_getTableColumns($data), + $this->_getTableName(), + implode(' AND ', $where), + $order + ); } - return sprintf($sql, $this->_getTableName(), implode(', ', $columns), - implode(' AND ', $where)); - } - - /** - * Retorna uma query SQL para a operação DELETE. Utiliza para isso o - * atributo identidade "id" (caso seja passada uma instância de CoreExt_Entity - * como parâmetro) ou o valor inteiro passado como parâmetro. - * - * Uma query gerada por esse método segue a forma: - * - * DELETE FROM [schema.]table WHERE id = 'idValue'; - * - * - * @param mixed $instance - * @return string - */ - protected function _getDeleteStatment($pkToDelete) - { - $sql = 'DELETE FROM %s WHERE %s'; - - $where = array(); - foreach ($pkToDelete as $key => $value) { - $whereName = $this->_getTableColumn($key); - $where[] = sprintf("%s = '%s'", $whereName, $value); + /** + * Retorna uma query SQL de recuperação de registro baseada na identidade. + * + * Converte o argumento $pkey para float, como forma de + * evitar os problemas do tipo int em ambientes 32 bit (mais especificamente, + * a ausência de um tipo long). + * + * @link http://php.net/manual/en/language.types.integer.php + * @link http://php.net/manual/en/function.intval.php + * + * @param array|long $pkey + * + * @return string + */ + protected function _getFindStatment($pkey) + { + $where = []; + + if (!is_array($pkey)) { + $keys = array_keys($this->_primaryKey); + $pkey = [ + array_shift($keys) => $pkey + ]; + } + + foreach ($pkey as $key => $pk) { + $whereName = $this->_getTableColumn($key); + $where[] = sprintf('%s = \'%s\'', $whereName, $pk); + } + + return sprintf( + 'SELECT %s FROM %s WHERE %s', + $this->_getTableColumns(), + $this->_getTableName(), + implode(' AND ', $where) + ); } - return sprintf($sql, $this->_getTableName(), implode(' AND ', $where)); - } - - /** - * Retorna todos os registros como objetos CoreExt_Entity retornados pela - * query de _getFindAllStatment(). - * - * @param array $columns Atributos a serem carregados. O atributo id é sempre carregado. - * @param array $where - * @param array $orderBy - * @param array $addColumnIdIfNotSet Se true, adiciona a coluna 'id' caso não esteja definido no array $columns - * @return array - * @todo Problema potencial com busca em registros com compount key. Testar. - */ - public function findAll(array $columns = array(), array $where = array(), array $orderBy = array(), $addColumnIdIfNotSet = true) - { - // Inverte chave valor, permitindo array simples como array('nome') - if (0 < count($columns)) { - $columns = array_flip($columns); - if (!isset($columns['id']) && $addColumnIdIfNotSet) { - $columns['id'] = TRUE; - } + /** + * Retorna uma query SQL para a operação INSERT. Utiliza para isso os + * atributos da instância CoreExt_Entity, com o cuidado de remover o + * campo identidade. + * + * Uma query gerada por esse método segue a forma: + * + * INSERT INTO [schema.]table (column) VALUES ('value'); + * + * + * @param CoreExt_Entity $instance + * + * @return string + */ + protected function _getSaveStatment(CoreExt_Entity $instance) + { + $sql = 'INSERT INTO %s (%s) VALUES (%s)'; + + //Remove campos null + $data = $this->_cleanNullValuesToSave($instance); + + // Pega apenas os valores do array + $values = array_values($data); + + // Colunas para formar a query + $columns = $this->_getTableColumns($data); + + // Trata os valores NULL diferentemente dos outros, para evitar erro + // de execução query + $valuesStmt = []; + + for ($i = 0, $count = count($values); $i < $count; $i++) { + $value = $values[$i]; + $valuesStmt[] = sprintf('\'%s\'', pg_escape_string($value)); + } + + $valuesStmt = join(', ', $valuesStmt); + + return sprintf($sql, $this->_getTableName(), $columns, $valuesStmt); } - // Reseta o locale para o default (en_US) - $this->getLocale()->resetLocale(); + /** + * Retorna uma query SQL para a operação UPDATE. Utiliza para isso os + * atributos da instância CoreExt_Entity, usando o atributo identidade + * para especificar qual registro atualizar na tabela. + * + * Uma query gerada por esse método segue a forma: + * + * UPDATE [schema.]table SET column='value' WHERE id = 'idValue'; + * + * + * @param CoreExt_Entity $instance + * + * @return string + */ + protected function _getUpdateStatment(CoreExt_Entity $instance) + { + $sql = 'UPDATE %s SET %s WHERE %s'; + + // Convert a entity em array, traz o array com dados formatados + $data = $this->_getDbAdapter()->formatValues($instance->toDataArray()); + + // Remove o campo identidade e campos não-persistentes + $data = $this->_cleanData($data); + + if (empty($data)) { + return ''; + } + + // Trata os valores NULL diferentemente dos outros, para evitar erro + // de execução query + $columns = []; + + foreach ($data as $key => $value) { + $columnName = $this->_getTableColumn($key); + $replaceString = '%s = \'%s\''; - $this->_getDbAdapter()->Consulta($this->_getFindAllStatment($columns, $where, $orderBy)); - $list = array(); + if (is_null($value) || (0 == $value && $instance->_isReferenceDataMapper($key))) { + $value = 'NULL'; + $replaceString = '%s = %s'; + } - // Retorna o locale para o usado no restante da aplicação - $this->getLocale()->setLocale(); + $columns[] = sprintf($replaceString, $columnName, pg_escape_string($value)); + } + + $where = []; + $keyToUpdate = $this->buildKeyToFind($instance); - while ($this->_getDbAdapter()->ProximoRegistro()) { - $list[] = $this->_createEntityObject($this->_getDbAdapter()->Tupla()); + foreach ($keyToUpdate as $key => $value) { + $whereName = $this->_getTableColumn($key); + $where[] = sprintf('%s = \'%s\'', $whereName, $value); + } + + return sprintf( + $sql, + $this->_getTableName(), + implode(', ', $columns), + implode(' AND ', $where) + ); } - return $list; - } - - - /** - * Retorna todos os registros como objetos CoreExt_Entity retornados pela - * query de _getFindAllStatment() (usando consulta preparada, util para evitar sql injection). - * - * @param array $columns Atributos a serem carregados. O atributo id é sempre carregado. - * @param array $where Condicoes preparadas ex: array('arg1 = $1', 'arg2 = $2'); - * @param array $params Valor das condiçoes ($1, $2 ...) ex: array('1', '3'); - * @param array $orderBy - * @param array $addColumnIdIfNotSet Se true, adiciona a coluna 'id' caso não esteja definido no array $columns - * @return array - * @todo - */ - public function findAllUsingPreparedQuery(array $columns = array(), array $where = array(), array $params = array(), array $orderBy = array(), $addColumnIdIfNotSet = true) { - $list = array(); - - // Inverte chave valor, permitindo array simples como array('nome') - if (0 < count($columns)) { - $columns = array_flip($columns); - if (!isset($columns['id']) && $addColumnIdIfNotSet) { - $columns['id'] = TRUE; - } + /** + * Retorna uma query SQL para a operação DELETE. Utiliza para isso o + * atributo identidade "id" (caso seja passada uma instância de CoreExt_Entity + * como parâmetro) ou o valor inteiro passado como parâmetro. + * + * Uma query gerada por esse método segue a forma: + * + * DELETE FROM [schema.]table WHERE id = 'idValue'; + * + * + * @param mixed $instance + * + * @return string + */ + protected function _getDeleteStatment($pkToDelete) + { + $sql = 'DELETE FROM %s WHERE %s'; + + $where = []; + + foreach ($pkToDelete as $key => $value) { + $whereName = $this->_getTableColumn($key); + $where[] = sprintf('%s = \'%s\'', $whereName, $value); + } + + return sprintf($sql, $this->_getTableName(), implode(' AND ', $where)); } - // Reseta o locale para o default (en_US) - $this->getLocale()->resetLocale(); + /** + * Retorna todos os registros como objetos CoreExt_Entity retornados pela + * query de _getFindAllStatment(). + * + * @param array $columns Atributos a serem carregados. O atributo id é sempre carregado. + * @param array $where + * @param array $orderBy + * @param bool $addColumnIdIfNotSet Se true, adiciona a coluna 'id' caso não esteja definido no array $columns + * + * @return array + * + * @throws Exception + */ + public function findAll(array $columns = [], array $where = [], array $orderBy = [], $addColumnIdIfNotSet = true) + { + // Inverte chave valor, permitindo array simples como array('nome') + if (0 < count($columns)) { + $columns = array_flip($columns); + + if (!isset($columns['id']) && $addColumnIdIfNotSet) { + $columns['id'] = true; + } + } + + // Reseta o locale para o default (en_US) + $this->getLocale()->resetLocale(); + $this->_getDbAdapter()->Consulta($this->_getFindAllStatment($columns, $where, $orderBy)); + + $list = []; - $sql = $this->_getFindAllStatment($columns, $where, $orderBy); + // Retorna o locale para o usado no restante da aplicação + $this->getLocale()->setLocale(); - if ($this->_getDbAdapter()->execPreparedQuery($sql, $params) != false) { - // Retorna o locale para o usado no restante da aplicação - $this->getLocale()->setLocale(); + while ($this->_getDbAdapter()->ProximoRegistro()) { + $list[] = $this->_createEntityObject($this->_getDbAdapter()->Tupla()); + } - while ($this->_getDbAdapter()->ProximoRegistro()) { - $list[] = $this->_createEntityObject($this->_getDbAdapter()->Tupla()); - } + return $list; } - return $list; - } - - - /** - * Retorna um registro que tenha como identificador (chave única ou composta) - * o valor dado por $pkey. - * - * @param array|long $pkey - * @return CoreExt_Entity - * @throws Exception - */ - public function find($pkey) - { - $this->_getDbAdapter()->Consulta($this->_getFindStatment($pkey)); - if (FALSE === $this->_getDbAdapter()->ProximoRegistro()) { - throw new Exception('Nenhum registro encontrado com a(s) chaves(s) informada(s).'); + /** + * Retorna todos os registros como objetos CoreExt_Entity retornados pela + * query de _getFindAllStatment() (usando consulta preparada, util para evitar sql injection). + * + * @param array $columns Atributos a serem carregados. O atributo id é sempre carregado. + * @param array $where Condicoes preparadas ex: array('arg1 = $1', 'arg2 = $2'); + * @param array $params Valor das condiçoes ($1, $2 ...) ex: array('1', '3'); + * @param array $orderBy + * @param bool $addColumnIdIfNotSet Se true, adiciona a coluna 'id' caso não esteja definido no array $columns + * + * @return array + * + * @throws Exception + */ + public function findAllUsingPreparedQuery(array $columns = [], array $where = [], array $params = [], array $orderBy = [], $addColumnIdIfNotSet = true) + { + $list = []; + + // Inverte chave valor, permitindo array simples como array('nome') + if (0 < count($columns)) { + $columns = array_flip($columns); + + if (!isset($columns['id']) && $addColumnIdIfNotSet) { + $columns['id'] = true; + } + } + + // Reseta o locale para o default (en_US) + $this->getLocale()->resetLocale(); + + $sql = $this->_getFindAllStatment($columns, $where, $orderBy); + + if ($this->_getDbAdapter()->execPreparedQuery($sql, $params) != false) { + // Retorna o locale para o usado no restante da aplicação + $this->getLocale()->setLocale(); + + while ($this->_getDbAdapter()->ProximoRegistro()) { + $list[] = $this->_createEntityObject($this->_getDbAdapter()->Tupla()); + } + } + + return $list; } - return $this->_createEntityObject($this->_getDbAdapter()->Tupla()); - } /** * Retorna um registro que tenha como identificador (chave única ou composta) * o valor dado por $pkey. * - * @param array|long $pkey + * @param array|long $pkey + * * @return CoreExt_Entity + * + * @throws Exception + */ + public function find($pkey) + { + $this->_getDbAdapter()->Consulta($this->_getFindStatment($pkey)); + + if (false === $this->_getDbAdapter()->ProximoRegistro()) { + throw new Exception('Nenhum registro encontrado com a(s) chaves(s) informada(s).'); + } + + return $this->_createEntityObject($this->_getDbAdapter()->Tupla()); + } + + /** + * Retorna um registro que tenha como identificador (chave única ou composta) + * o valor dado por $pkey. + * + * @param int|array $pkey + * + * @return bool + * * @throws Exception */ public function exists($pkey) { $this->_getDbAdapter()->Consulta($this->_getFindStatment($pkey)); - if (FALSE === $this->_getDbAdapter()->ProximoRegistro()) { + if (false === $this->_getDbAdapter()->ProximoRegistro()) { return false; } + return true; } - /** - * Salva ou atualiza um registro através de uma instância de CoreExt_Entity. - * - * @param CoreExt_Entity $instance - * @return bool - * @throws CoreExt_DataMapper_Exception|Exception - */ - public function save(CoreExt_Entity $instance) - { - /* - if (!$instance->isValid()) { - throw new Exception('A instânca de "' . get_class($instance) . '" contém erros de validação.'); - }*/ - - // Coumpound key, todos os valores precisam estar setados, seja para - // INSERT ou UPDATE. A instância precisa ser marcada explicitamente - // como "old" para que UPDATE seja chamado. - $hasValuePk = true; - - foreach ($this->_primaryKey as $key => $pk) { - $value = $instance->get($key); - if (!isset($value)) { - $hasValuePk = false; - } + /** + * Salva ou atualiza um registro através de uma instância de CoreExt_Entity. + * + * @param CoreExt_Entity $instance + * + * @return bool + * + * @throws CoreExt_DataMapper_Exception|Exception + */ + public function save(CoreExt_Entity $instance) + { + // Coumpound key, todos os valores precisam estar setados, seja para + // INSERT ou UPDATE. A instância precisa ser marcada explicitamente + // como "old" para que UPDATE seja chamado. + $hasValuePk = true; + + foreach ($this->_primaryKey as $key => $pk) { + $value = $instance->get($key); + + if (!isset($value)) { + $hasValuePk = false; + } + } + + if ($hasValuePk) { + if ($this->exists($this->buildKeyToFind($instance))) { + $instance->markOld(); + } + } + + @session_start(); + $pessoa_logada = $_SESSION['id_pessoa']; + @session_write_close(); + + if ($instance->isNew()) { + $returning = ' RETURNING ' . implode(',', array_values($this->_primaryKey)); + $return = $this->_getDbAdapter()->Consulta($this->_getSaveStatment($instance) . $returning); + $result = pg_fetch_row($return); + $id = $result[0]; + + if ($id) { + $tmpEntry = $this->find($id); + $info = $tmpEntry->toDataArray(); + $auditoria = new clsModulesAuditoriaGeral($this->_tableName, $pessoa_logada, $id); + $auditoria->inclusao($info); + } + } elseif (!$instance->isNew()) { + $pkSave = $this->buildKeyToFind($instance); + + $tmpEntry = $this->find($pkSave); + $oldInfo = $tmpEntry->toDataArray(); + + $return = $this->_getDbAdapter()->Consulta($this->_getUpdateStatment($instance)); + + $tmpEntry = $this->find($pkSave); + $newInfo = $tmpEntry->toDataArray(); + + $keys = array_keys($this->_primaryKey); + $auditoria = new clsModulesAuditoriaGeral($this->_tableName, $pessoa_logada, $instance->get(array_shift($keys))); + $auditoria->alteracao($oldInfo, $newInfo); + } + + return $return; + + // Retorna o locale para o usado no restante da aplicação + $this->getLocale()->setLocale(); } - if ($hasValuePk) { - if ($this->exists($this->buildKeyToFind($instance))){ - $instance->markOld(); - } + /** + * Apaga um registro através de uma instância CoreExt_Entity. Pode apagar + * recebendo uma instância com as chaves primárias setadas ou um array + * associativo de chaves primárias e seus valores. + * + * Exemplo: + * + * 1, 'pk2' => 2)); + * $dataMapper = new CoreExt_DataMapper(); + * + * // Por valor do campo identidade 'id' + * $dataMapper->delete(1); + * + * // Pelas chaves primárias de uma instância + * $dataMapper->delete($instance); + * + * // Por um array de chaves associativas de chaves primárias + * $dataMapper->delete(array('pk1' => 1, 'pk2' => 2)); + * + * + * @param mixed $instance + * + * @return bool + * + * @throws Exception + */ + public function delete($instance) + { + $info = []; + $pkToDelete = $this->buildKeyToFind($instance); + + if ((is_object($instance) && $instance->id) || (!is_object($instance) && $instance)) { + $tmpEntry = $this->find($pkToDelete); + $info = $tmpEntry->toDataArray(); + } + + $return = $this->_getDbAdapter()->Consulta($this->_getDeleteStatment($pkToDelete)); + + if (count($info)) { + @session_start(); + $pessoa_logada = $_SESSION['id_pessoa']; + @session_write_close(); + + $auditoria = new clsModulesAuditoriaGeral($this->_tableName, $pessoa_logada, array_shift(array_values($instance))); + $auditoria->exclusao($info); + } + + return $return; } - @session_start(); - $pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); - - if ($instance->isNew()) { - $returning = ' RETURNING '.implode(',', array_values($this->_primaryKey)); - $return = $this->_getDbAdapter()->Consulta($this->_getSaveStatment($instance). $returning); - $result = pg_fetch_row($return); - $id = $result[0]; - if ($id) { - $tmpEntry = $this->find($id); - $info = $tmpEntry->toDataArray(); - $auditoria = new clsModulesAuditoriaGeral($this->_tableName, $pessoa_logada, $id); - $auditoria->inclusao($info); - } + + /** + * Retorna um array com chaves do mapper. + * + * @return array + */ + + public function buildKeyToFind($instance) + { + $pkInstance = []; + + if (is_numeric($instance)) { + $pkInstance[array_shift(array_keys($this->_primaryKey))] = $instance; + } elseif (is_object($instance)) { + foreach ($this->_primaryKey as $key => $item) { + $pkInstance[$key] = $instance->get($key); + } + } + + return $pkInstance; } - elseif (!$instance->isNew()) { - $pkSave = $this->buildKeyToFind($instance); - $tmpEntry = $this->find($pkSave); - $oldInfo = $tmpEntry->toDataArray(); + /** + * Retorna uma nova instância de CoreExt_Entity. A instância criada não + * produz efeito algum no comportamento de CoreExt_DataMapper. + * + * @return CoreExt_Entity + */ + public function createNewEntityInstance(array $data = []) + { + return new $this->_entityClass($data); + } - $return = $this->_getDbAdapter()->Consulta($this->_getUpdateStatment($instance)); + protected function _cleanData(array $data) + { + foreach ($this->_primaryKey as $key => $val) { + if (array_key_exists($key, $data)) { + unset($data[$key]); + } + } - $tmpEntry = $this->find($pkSave); - $newInfo = $tmpEntry->toDataArray(); + // Remove dados não-persistíveis + foreach ($this->_notPersistable as $field) { + if (array_key_exists($field, $data)) { + unset($data[$field]); + } + } - $keys = array_keys($this->_primaryKey); - $auditoria = new clsModulesAuditoriaGeral($this->_tableName, $pessoa_logada, $instance->get(array_shift($keys))); - $auditoria->alteracao($oldInfo, $newInfo); + return $data; } - return $return; - - // Retorna o locale para o usado no restante da aplicação - $this->getLocale()->setLocale(); - } - - /** - * Apaga um registro através de uma instância CoreExt_Entity. Pode apagar - * recebendo uma instância com as chaves primárias setadas ou um array - * associativo de chaves primárias e seus valores. - * - * Exemplo: - * - * 1, 'pk2' => 2)); - * $dataMapper = new CoreExt_DataMapper(); - * - * // Por valor do campo identidade 'id' - * $dataMapper->delete(1); - * - * // Pelas chaves primárias de uma instância - * $dataMapper->delete($instance); - * - * // Por um array de chaves associativas de chaves primárias - * $dataMapper->delete(array('pk1' => 1, 'pk2' => 2)); - * - * - * @param mixed $instance - * @return bool - */ - public function delete($instance) - { - $info = array(); - $pkToDelete = $this->buildKeyToFind($instance); - if ((is_object($instance) && $instance->id) || (!is_object($instance) && $instance)) { - $tmpEntry = $this->find($pkToDelete); - $info = $tmpEntry->toDataArray(); - } - - $return = $this->_getDbAdapter()->Consulta($this->_getDeleteStatment($pkToDelete)); - - if (count($info)){ - @session_start(); - $pessoa_logada = $_SESSION['id_pessoa']; - @session_write_close(); + /** + * Remove campos null para realizar insert + */ + protected function _cleanNullValuesToSave(CoreExt_Entity $instance) + { + $data = $this->_getDbAdapter()->formatValues($instance->toDataArray()); + foreach ($data as $key => $val) { + if (is_null($val) || ($val == 0 && $instance->_isReferenceDataMapper($key))) { + unset($data[$key]); + } + } - $auditoria = new clsModulesAuditoriaGeral($this->_tableName, $pessoa_logada, array_shift(array_values($instance))); - $auditoria->exclusao($info); - } - - return $return; - } - - /** - * Retorna um array com chaves do mapper. - * - * @return array - */ - - public function buildKeyToFind($instance){ - $pkInstance = array(); - if (is_numeric($instance)){ - $pkInstance[array_shift(array_keys($this->_primaryKey))] = $instance; - } else if (is_object($instance)) { - foreach ($this->_primaryKey as $key => $item) { - $pkInstance[$key] = $instance->get($key); - } - } - - return $pkInstance; - } - - /** - * Retorna uma nova instância de CoreExt_Entity. A instância criada não - * produz efeito algum no comportamento de CoreExt_DataMapper. - * - * @return CoreExt_Entity - */ - public function createNewEntityInstance(array $data = array()) - { - return new $this->_entityClass($data); - } - - /** - */ - protected function _cleanData(array $data) - { - foreach ($this->_primaryKey as $key => $val) { - if (array_key_exists($key, $data)) { - unset($data[$key]); - } + return $data; } - // Remove dados não-persistíveis - foreach ($this->_notPersistable as $field) { - if (array_key_exists($field, $data)) { - unset($data[$field]); - } + /** + * Cria um objeto CoreExt_Entity com os valores dos campos relacionais + * mapeados para os atributos da instância. + * + * @param array $data + * + * @return CoreExt_Entity + */ + protected function _createEntityObject(array $data) + { + $instance = $this->createNewEntityInstance(); + $instance->markOld(); + $instance = $this->_mapData($data, $instance); + + return $instance; } - return $data; - } - - /* - * Remove campos null para realizar insert - */ - protected function _cleanNullValuesToSave(CoreExt_Entity $instance){ - $data = $this->_getDbAdapter()->formatValues($instance->toDataArray()); - foreach ($data as $key => $val) { - if (is_null($val) || ($val == 0 && $instance->_isReferenceDataMapper($key)) ){ - unset($data[$key]); - } + /** + * Mapeia os campos relacionais para os atributos de uma instância de + * CoreExt_Entity. + * + * @param array $data + * @param CoreExt_Entity $instance + * + * @return CoreExt_Entity A instância com os atributos mapeados + */ + protected function _mapData($data, CoreExt_Entity $instance) + { + foreach ($data as $key => $value) { + try { + $instance->$key = $value; + } catch (CoreExt_Exception_InvalidArgumentException $e) { + // Caso o campo não tenha um atributo correspondente, procura no + // mapa de atributos pelo equivalente e atribue. + if (false !== ($index = array_search($key, $this->_attributeMap))) { + $instance->$index = $value; + } + } + } + + return $instance; } - return $data; - } - - /** - * Cria um objeto CoreExt_Entity com os valores dos campos relacionais - * mapeados para os atributos da instância. - * - * @param array $data - * @return CoreExt_Entity - */ - protected function _createEntityObject(array $data) - { - $instance = $this->createNewEntityInstance(); - $instance->markOld(); - $instance = $this->_mapData($data, $instance); - return $instance; - } - - /** - * Mapeia os campos relacionais para os atributos de uma instância de - * CoreExt_Entity. - * - * @param array $data - * @param CoreExt_Entity $instance - * @return CoreExt_Entity A instância com os atributos mapeados - */ - protected function _mapData($data, CoreExt_Entity $instance) - { - foreach ($data as $key => $value) { - try { - $instance->$key = $value; - } - catch (CoreExt_Exception_InvalidArgumentException $e) { - // Caso o campo não tenha um atributo correspondente, procura no - // mapa de atributos pelo equivalente e atribue. - if (FALSE !== ($index = array_search($key, $this->_attributeMap))) { - $instance->$index = $value; - } - } + /** + * Setter. + * + * @param CoreExt_Locale $instance + * + * @return CoreExt_DataMapper Provê interface fluída + */ + public function setLocale(CoreExt_Locale $instance) + { + $this->_locale = $instance; + + return $this; } - return $instance; - } - - /** - * Setter. - * @param CoreExt_Locale $instance - * @return CoreExt_DataMapper Provê interface fluída - */ - public function setLocale(CoreExt_Locale $instance) - { - $this->_locale = $instance; - return $this; - } - - /** - * Getter. - * @return CoreExt_Locale - */ - public function getLocale() - { - if (is_null($this->_locale)) { - require_once 'CoreExt/Locale.php'; - $this->setLocale(CoreExt_Locale::getInstance()); + + /** + * Getter. + * + * @return CoreExt_Locale + */ + public function getLocale() + { + if (is_null($this->_locale)) { + require_once 'CoreExt/Locale.php'; + $this->setLocale(CoreExt_Locale::getInstance()); + } + + return $this->_locale; } - return $this->_locale; - } } diff --git a/ieducar/lib/CoreExt/DataMapper/Exception.php b/ieducar/lib/CoreExt/DataMapper/Exception.php index 1024c4258c..683b53a897 100644 --- a/ieducar/lib/CoreExt/DataMapper/Exception.php +++ b/ieducar/lib/CoreExt/DataMapper/Exception.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Exception - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Exception.php'; -/** - * CoreExt_DataMapper_Exception class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_DataMapper - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_DataMapper_Exception extends CoreExt_Exception { -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Entity.php b/ieducar/lib/CoreExt/Entity.php index 8de9394665..2738fe0eff 100644 --- a/ieducar/lib/CoreExt/Entity.php +++ b/ieducar/lib/CoreExt/Entity.php @@ -1,1187 +1,1267 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Entity - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Entity/Validatable.php'; -/** - * CoreExt_Entity abstract class. - * - * Um layer supertype para objetos da camada de domínio de todos os namespaces - * da aplicação. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @link http://martinfowler.com/eaaCatalog/layerSupertype.html - * @package CoreExt_Entity - * @since Classe disponível desde a versão 1.1.0 - * @todo Possibilitar uso opcional do campo identidade, útil para casos - * de compound primary keys - * @version @@package_version@@ - */ abstract class CoreExt_Entity implements CoreExt_Entity_Validatable { - /** - * Define se uma instância é "nova" ou "velha" (caso seja carregada via - * CoreExt_DataMapper). - * @var bool - */ - protected $_new = TRUE; - - /** - * Array associativo onde os índices se comportarão como atributos públicos - * graças a implementação dos métodos mágicos de overload. - * - * @var array - */ - protected $_data = array(); - - /** - * Array associativo onde os índices identificam o tipo de dado de uma - * propriedade pública tal qual declarada em $_data. - * - * @var array - * @see _getValue() Contém a lista de tipos atualmente suportados - */ - protected $_dataTypes = array(); - - /** - * @var CoreExt_DataMapper - */ - protected $_dataMapper = NULL; - - /** - * Array associativo para referências a objetos que serão carregados com - * lazy load. - * - * Uma reference pode ser de um dos tipos: - * - CoreExt_DataMapper - * - CoreExt_Enum - * - * Toda vez que uma reference for requisitada e acessada pela primeira vez, - * ela não fará mais lookups (buscas SQL, acesso a arrays de valores). - * - * - * array( - * 'value' => 1, - * 'class' => 'AreaConhecimento_Model_AreaDataMapper', - * 'file' => 'AreaConhecimento/Model/AreaDataMapper.php' - * ) - * ); - * - * - * @link http://martinfowler.com/eaaCatalog/lazyLoad.html Lazy load - * @var array - */ - protected $_references = array(); - - /** - * Coleção de validadores para as propriedades $_data de CoreExt_Entity. - * @var array - */ - protected $_validators = array(); - - /** - * Coleção de mensagens de erro retornado pelos validadores de $_validators - * durante a execução do método isValid(). - * - * @var array - */ - protected $_errors = array(); - - /** - * Array com instâncias para classes pertecentes ao namespace iEd_*. - * - * - * array( - * 'class' => 'stdClass', - * 'instance' => NULL, - * ) - * ); - * - * - * @see CoreExt_Entity#addClassToStorage($class, $instance = NULL, $file = NULL) - * @var array - */ - protected static $_classStorage = array(); - - /** - * @var CoreExt_Locale - */ - protected $_locale = NULL; - - /** - * Construtor. - * - * @param array $options Array associativo para inicializar os valores dos - * atributos do objeto - */ - public function __construct($options = array()) - { - $this->_createIdentityField() - ->setOptions($options); - } - - /** - * Adiciona um campo identidade como atributo da instância. - * - * @link http://martinfowler.com/eaaCatalog/identityField.html - * @return CoreExt_Entity Provê interface fluída - */ - protected function _createIdentityField() - { - $id = array('id' => NULL); - $this->_data = array_merge($id, $this->_data); - return $this; - } - - /** - * Atribui valor para cada atributo da classe que tenha correspondência com - * o indice do array $options passado como argumento. - * - * @param array $options - * @return CoreExt_Entity Provê interface fluída - */ - public function setOptions($options = array()) - { - foreach ($options as $key => $value) { - $this->$key = $value; - } - return $this; - } - - /** - * Implementação do método mágico __set(). - * - * Esse método é um pouco complicado devido a lógica de configuração das - * referências para lazy loading. - * - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string $key - * @param mixed $val - * @return bool|NULL TRUE caso seja uma referência válida ou NULL para o fluxo - * normal do método - */ - public function __set($key, $val) - { - if ($this->_hasReference($key)) { - // Se houver uma referência e ela pode ser NULL, atribui NULL quando - // a referência for carregada por CoreExt_DataMapper (new = FALSE). - // Se for uma referência a CoreExt_DataMapper, 0 será equivalente a NULL. - // Aqui, nem instância tem, nem lazy load acontecerá. - if ( - is_null($val) || (FALSE === $this->_new && "NULL" === $val) - || ($this->_isReferenceDataMapper($key) && (is_numeric($val) && 0 === $val)) - ) - { - $this->_references[$key]['value'] = NULL; - return TRUE; - } - - // Se a referência for numérica, usa-a, marcando apenas a referência e - // deixando o atributo NULL para o lazy load. - if (is_numeric($val)) { - $this->_references[$key]['value'] = $this->_getValue($key, $val); - return TRUE; - } - - // Se for uma instância de CoreExt_Entity e tiver um identificador, - // usa-o. Referências sem um valor poderão ser consideradas como novas - // numa implementação de save() de CoreExt_DataMapper que leve em - // consideração as referências, salvando-as ou atualizando-as. - elseif ($val instanceof CoreExt_Entity && isset($val->id)) { - $this->_references[$key]['value'] = $this->_getValue($key, $val->id); - // Não retorna, queremos aproveitar a instância para não mais carregá-la - // em __get(). - } - - // Aqui, identificamos que o atributo não se encaixa em nenhum dos itens - // anteriores, lançando um Exceção. Como CoreExt_Enum não contém um - // estado (o valor corrente, por ser um Enum!), aceitamos apenas - // instâncias de CoreExt_Entity como parâmetro - elseif (!($val instanceof CoreExt_Entity)) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException('O argumento passado para o atributo "' . $key - . '" é inválido. Apenas os tipos "int" e "CoreExt_Entity" são suportados.'); - } + /** + * Define se uma instância é "nova" ou "velha" (caso seja carregada via + * CoreExt_DataMapper). + * + * @var bool + */ + protected $_new = true; + + /** + * Array associativo onde os índices se comportarão como atributos públicos + * graças a implementação dos métodos mágicos de overload. + * + * @var array + */ + protected $_data = []; + + /** + * Array associativo onde os índices identificam o tipo de dado de uma + * propriedade pública tal qual declarada em $_data. + * + * @var array + * + * @see _getValue() Contém a lista de tipos atualmente suportados + */ + protected $_dataTypes = []; + + /** + * @var CoreExt_DataMapper + */ + protected $_dataMapper = null; + + /** + * Array associativo para referências a objetos que serão carregados com + * lazy load. + * + * Uma reference pode ser de um dos tipos: + * - CoreExt_DataMapper + * - CoreExt_Enum + * + * Toda vez que uma reference for requisitada e acessada pela primeira vez, + * ela não fará mais lookups (buscas SQL, acesso a arrays de valores). + * + * + * array( + * 'value' => 1, + * 'class' => 'AreaConhecimento_Model_AreaDataMapper', + * 'file' => 'AreaConhecimento/Model/AreaDataMapper.php' + * ) + * ); + * + * + * @link http://martinfowler.com/eaaCatalog/lazyLoad.html Lazy load + * + * @var array + */ + protected $_references = []; + + /** + * Coleção de validadores para as propriedades $_data de CoreExt_Entity. + * + * @var array + */ + protected $_validators = []; + + /** + * Coleção de mensagens de erro retornado pelos validadores de $_validators + * durante a execução do método isValid(). + * + * @var array + */ + protected $_errors = []; + + /** + * Array com instâncias para classes pertecentes ao namespace iEd_*. + * + * + * array( + * 'class' => 'stdClass', + * 'instance' => NULL, + * ) + * ); + * + * + * @see CoreExt_Entity#addClassToStorage($class, $instance = NULL, $file = NULL) + * + * @var array + */ + protected static $_classStorage = []; + + /** + * @var CoreExt_Locale + */ + protected $_locale = null; + + /** + * Construtor. + * + * @param array $options Array associativo para inicializar os valores dos + * atributos do objeto + */ + public function __construct($options = []) + { + $this->_createIdentityField() + ->setOptions($options); } - // Se o atributo não existir, lança exceção - if (!array_key_exists($key, $this->_data)) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException('A propriedade ' - . $key . ' não existe em ' . __CLASS__ . '.'); + /** + * Adiciona um campo identidade como atributo da instância. + * + * @link http://martinfowler.com/eaaCatalog/identityField.html + * + * @return CoreExt_Entity Provê interface fluída + */ + protected function _createIdentityField() + { + $id = ['id' => null]; + $this->_data = array_merge($id, $this->_data); + + return $this; } - // Se for string vazia, o valor é NULL - if ('' == trim($val)) { - $this->_data[$key] = NULL; + /** + * Atribui valor para cada atributo da classe que tenha correspondência com + * o indice do array $options passado como argumento. + * + * @param array $options + * + * @return CoreExt_Entity Provê interface fluída + */ + public function setOptions($options = []) + { + foreach ($options as $key => $value) { + $this->$key = $value; + } + + return $this; } - // Chama _getValue(), para fazer conversões que forem necessárias - else { - $this->_data[$key] = $this->_getValue($key, $val); + + /** + * Implementação do método mágico __set(). + * + * Esse método é um pouco complicado devido a lógica de configuração das + * referências para lazy loading. + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string $key + * @param mixed $val + * + * @return bool|NULL TRUE caso seja uma referência válida ou NULL para o fluxo + * normal do método + */ + public function __set($key, $val) + { + if ($this->_hasReference($key)) { + // Se houver uma referência e ela pode ser NULL, atribui NULL quando + // a referência for carregada por CoreExt_DataMapper (new = FALSE). + // Se for uma referência a CoreExt_DataMapper, 0 será equivalente a NULL. + // Aqui, nem instância tem, nem lazy load acontecerá. + if ( + is_null($val) || (false === $this->_new && 'NULL' === $val) + || ($this->_isReferenceDataMapper($key) && (is_numeric($val) && 0 === $val)) + ) { + $this->_references[$key]['value'] = null; + + return true; + } + + // Se a referência for numérica, usa-a, marcando apenas a referência e + // deixando o atributo NULL para o lazy load. + if (is_numeric($val)) { + $this->_references[$key]['value'] = $this->_getValue($key, $val); + + return true; + } + + // Se for uma instância de CoreExt_Entity e tiver um identificador, + // usa-o. Referências sem um valor poderão ser consideradas como novas + // numa implementação de save() de CoreExt_DataMapper que leve em + // consideração as referências, salvando-as ou atualizando-as. + elseif ($val instanceof CoreExt_Entity && isset($val->id)) { + $this->_references[$key]['value'] = $this->_getValue($key, $val->id); + // Não retorna, queremos aproveitar a instância para não mais carregá-la + // em __get(). + } + + // Aqui, identificamos que o atributo não se encaixa em nenhum dos itens + // anteriores, lançando um Exceção. Como CoreExt_Enum não contém um + // estado (o valor corrente, por ser um Enum!), aceitamos apenas + // instâncias de CoreExt_Entity como parâmetro + elseif (!($val instanceof CoreExt_Entity)) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException( + 'O argumento passado para o atributo "' . $key + . '" é inválido. Apenas os tipos "int" e "CoreExt_Entity" são suportados.' + ); + } + } + + // Se o atributo não existir, lança exceção + if (!array_key_exists($key, $this->_data)) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException( + 'A propriedade ' . $key . ' não existe em ' . __CLASS__ . '.' + ); + } + + // Se for string vazia, o valor é NULL + if ('' == trim($val)) { + $this->_data[$key] = null; + } // Chama _getValue(), para fazer conversões que forem necessárias + else { + $this->_data[$key] = $this->_getValue($key, $val); + } } - } - - /** - * Implementação do método mágico __get(). - * - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string $key - * @return mixed - */ - public function __get($key) - { - if ('id' === $key) { - return floatval($this->_data[$key]) > 0 ? - floatval($this->_data[$key]) : NULL; + + /** + * Implementação do método mágico __get(). + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string $key + * + * @return mixed + */ + public function __get($key) + { + if ('id' === $key) { + return floatval($this->_data[$key]) > 0 + ? floatval($this->_data[$key]) + : null; + } + + if ($this->_hasReference($key) && !isset($this->_data[$key])) { + $this->_data[$key] = $this->_loadReference($key); + } + + return $this->_data[$key]; } - if ($this->_hasReference($key) && !isset($this->_data[$key])) { - $this->_data[$key] = $this->_loadReference($key); + /** + * Getter. Não resolve referências com lazy load, ao invés disso, retorna + * o valor da referência. + * + * @param string $key + * + * @return mixed + */ + public function get($key) + { + if ($this->_hasReference($key)) { + return $this->_getReferenceValue($key); + } + + return $this->__get($key); } - return $this->_data[$key]; - } - - /** - * Getter. Não resolve referências com lazy load, ao invés disso, retorna - * o valor da referência. - * - * @param string $key - * @return mixed - */ - public function get($key) - { - if ($this->_hasReference($key)) { - return $this->_getReferenceValue($key); + /** + * Implementação do método mágico __isset(). + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string $key + * + * @return bool + */ + public function __isset($key) + { + $val = $this->get($key); + + return isset($val); } - return $this->__get($key); - } - - - /** - * Implementação do método mágico __isset(). - * - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string $key - * @return bool - */ - public function __isset($key) - { - $val = $this->get($key); - return isset($val); - } - - /** - * Implementação do método mágico __unset(). - * - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string $key - */ - public function __unset($key) - { - $this->_data[$key] = NULL; - } - - /** - * Implementação do método mágico __toString(). - * - * @link http://br2.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring - * @return string - */ - public function __toString() - { - return get_class($this); - } - - - /** - * Carrega um objeto de uma referência, usando o CoreExt_DataMapper - * especificado para tal. - * - * @param string $key - * @return CoreExt_Entity - * @todo Se mais classes puderem ser atribuídas como references, implementar - * algum design pattern para diminuir a complexidade ciclomática - * desse método e de setReferenceClass(). - * @todo Caso a classe não seja um CoreExt_DataMapper ou CoreExt_Enum, - * lançar uma Exception. - * @todo Referências CoreExt_Enum só podem ter seu valor atribuído na - * instanciação. Verificar se isso é desejado e ver possibilidade - * de flexibilizar esse comportamente. Ver para CoreExt_DataMapper - * também. - */ - protected function _loadReference($key) - { - $reference = $this->_references[$key]; - - // Se a referência tiver valor NULL - $value = $reference['value']; - if (in_array($value, array(NULL), true)) { - return $value; + + /** + * Implementação do método mágico __unset(). + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string $key + */ + public function __unset($key) + { + $this->_data[$key] = null; } - // Verifica se a API da classe para saber qual tipo de instanciação usar - $class = $reference['class']; - if ($this->_isReferenceDataMapper($key)) { - $class = new $class(); + /** + * Implementação do método mágico __toString(). + * + * @link http://br2.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring + * + * @return string + */ + public function __toString() + { + return get_class($this); } - elseif ($this->_isReferenceEnum($key)) { - $class = $class . '::getInstance()'; - eval('?>'); + + /** + * Carrega um objeto de uma referência, usando o CoreExt_DataMapper + * especificado para tal. + * + * @param string $key + * + * @return CoreExt_Entity + * + * @throws Exception + */ + protected function _loadReference($key) + { + $reference = $this->_references[$key]; + + // Se a referência tiver valor NULL + $value = $reference['value']; + + if (in_array($value, [null], true)) { + return $value; + } + + // Verifica se a API da classe para saber qual tipo de instanciação usar + $class = $reference['class']; + + if ($this->_isReferenceDataMapper($key)) { + $class = new $class(); + } elseif ($this->_isReferenceEnum($key)) { + $class = $class . '::getInstance()'; + eval('?>'); + } + + // Faz a chamada a API, recupera o valor original (objetos). Usa a instância + // da classe. + if ($class instanceof CoreExt_DataMapper) { + $return = $class->find($value); + } elseif ($class instanceof CoreExt_Enum) { + if (!isset($class[$value])) { + return null; + } + $return = $class[$value]; + } + + return $return; } - // Faz a chamada a API, recupera o valor original (objetos). Usa a instância - // da classe. - if ($class instanceof CoreExt_DataMapper) { - $return = $class->find($value); + /** + * Verifica se existe uma referência para uma certa chave $key. + * + * @param string $key + * + * @return bool + */ + protected function _hasReference($key) + { + return array_key_exists($key, $this->_references); } - elseif ($class instanceof CoreExt_Enum) { - if (!isset($class[$value])) { - return NULL; - } - $return = $class[$value]; + + /** + * Configura ou adiciona uma nova referência para possibilitar o lazy load + * entre objetos. + * + * @param string $key O nome do atributo que mapeia para a referência + * @param array $data O array com a especificação da referência + * + * @return CoreExt_Entity Provê interface fluída + * + * @throws CoreExt_Exception_InvalidArgumentException + */ + public function setReference($key, $data) + { + if (!array_key_exists($key, $this->_data)) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException( + 'Somente é possível ' . 'criar referências para atributos da classe.' + ); + } + + $layout = ['value' => null, 'class' => null, 'file' => null, 'null' => null]; + + $options = array_keys($layout); + $passedOptions = array_keys($data); + + if (0 < count($diff = array_diff($passedOptions, $options))) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException('' . implode(', ', $diff)); + } + + if (!array_key_exists($key, $this->_references)) { + $this->_references[$key] = $layout; + } + + if (isset($data['value'])) { + $this->setReferenceValue($key, $data['value']); + } + + if (isset($data['class'])) { + $this->setReferenceClass($key, $data['class']); + } + + if (isset($data['file'])) { + $this->setReferenceFile($key, $data['file']); + } + + return $this; } - return $return; - } - - /** - * Verifica se existe uma referência para uma certa chave $key. - * @param string $key - * @return bool - */ - protected function _hasReference($key) - { - return array_key_exists($key, $this->_references); - } - - /** - * Configura ou adiciona uma nova referência para possibilitar o lazy load - * entre objetos. - * - * @param string $key O nome do atributo que mapeia para a referência - * @param array $data O array com a especificação da referência - * @return CoreExt_Entity Provê interface fluída - * @throws CoreExt_Exception_InvalidArgumentException - */ - public function setReference($key, $data) - { - if (!array_key_exists($key, $this->_data)) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException('Somente é possível ' - . 'criar referências para atributos da classe.'); + /** + * Setter para o valor de referência de uma reference. + * + * @param string $key + * @param int $value + * + * @return CoreExt_Entity Provê interface fluída + */ + public function setReferenceValue($key, $value) + { + $this->_references[$key]['value'] = (int) $value; + + return $this; } - $layout = array('value' => NULL, 'class' => NULL, 'file' => NULL, 'null' => NULL); + /** + * Setter para uma classe ou nome de classe de um CoreExt_DataMapper da + * reference. + * + * @param string $key + * @param CoreExt_DataMapper|CoreExt_Enum|string $class + * + * @return CoreExt_Entity Provê interface fluída + * + * @throws CoreExt_Exception_InvalidArgumentException + */ + public function setReferenceClass($key, $class) + { + if (!is_string($class) && !($class instanceof CoreExt_DataMapper || $class instanceof CoreExt_Enum)) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException( + 'Uma classe de referência ' + . ' precisa ser especificada pelo seu nome (string), ou, uma instância de CoreExt_DataMapper ou CoreExt_Enum.' + ); + } + $this->_references[$key]['class'] = $class; - $options = array_keys($layout); - $passedOptions = array_keys($data); + return $this; + } - if (0 < count($diff = array_diff($passedOptions, $options))) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException("" . implode(', ', $diff)); + /** + * Setter para o arquivo da classe CoreExt_DataMapper da classe de reference + * informada por setReferenceClass. + * + * @param string $key + * @param int $value + * + * @return CoreExt_Entity Provê interface fluída + */ + public function setReferenceFile($key, $file) + { + $this->_references[$key]['file'] = $file; + + return $this; } - if (!array_key_exists($key, $this->_references)) { - $this->_references[$key] = $layout; + /** + * Getter. + * + * @param string $key + * + * @return mixed + */ + protected function _getReferenceValue($key) + { + return isset($this->_references[$key]['value']) ? $this->_references[$key]['value'] : null; } - if (isset($data['value'])) { - $this->setReferenceValue($key, $data['value']); + + /** + * Getter. + * + * @param string $key + * + * @return string + */ + protected function _getReferenceClass($key) + { + return isset($this->_references[$key]['class']) ? $this->_references[$key]['class'] : null; } - if (isset($data['class'])) { - $this->setReferenceClass($key, $data['class']); + + /** + * Verifica se a classe da referência é uma instância de CoreExt_DataMapper. + * + * @param string $key + * + * @return bool + */ + public function _isReferenceDataMapper($key) + { + $class = $this->_getReferenceClass($key); + $reference = isset($this->_references[$key]['file']) ? $this->_references[$key]['file'] : null; + + return $this->_isReferenceOf( + $class, + $reference, + 'CoreExt_DataMapper' + ); } - if (isset($data['file'])) { - $this->setReferenceFile($key, $data['file']); + + /** + * Verifica se a classe da referência é uma instância de CoreExt_Enum. + * + * @param string $key + * + * @return bool + */ + protected function _isReferenceEnum($key) + { + $class = $this->_getReferenceClass($key); + + return $this->_isReferenceOf( + $class, + $this->_references[$key]['file'], + 'CoreExt_Enum' + ); } - return $this; - } - - /** - * Setter para o valor de referência de uma reference. - * @param string $key - * @param int $value - * @return CoreExt_Entity Provê interface fluída - */ - public function setReferenceValue($key, $value) - { - $this->_references[$key]['value'] = (int) $value; - return $this; - } - - /** - * Setter para uma classe ou nome de classe de um CoreExt_DataMapper da - * reference. - * @param string $key - * @param CoreExt_DataMapper|CoreExt_Enum|string $class - * @return CoreExt_Entity Provê interface fluída - * @throws CoreExt_Exception_InvalidArgumentException - */ - public function setReferenceClass($key, $class) - { - if (!is_string($class) && !($class instanceof CoreExt_DataMapper || $class instanceof CoreExt_Enum)) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException('Uma classe de referência ' - . ' precisa ser especificada pelo seu nome (string), ou, uma instância de CoreExt_DataMapper ou CoreExt_Enum.'); + /** + * Verifica se a referência é subclasse de $parentClass. + * + * @param string $subClass + * @param string $subClassFile + * @param string $parentClass + * + * @return bool + */ + private function _isReferenceOf($subClass, $subClassFile, $parentClass) + { + static $required = []; + + if (is_string($subClass)) { + if (!in_array($subClassFile, $required)) { + // Inclui o arquivo com a definição de subclasse para que o interpretador + // tenha o símbolo de comparação. + require_once $subClassFile; + $required[] = $subClassFile; + } + + return (is_subclass_of($subClass, $parentClass)); + } + + return false; } - $this->_references[$key]['class'] = $class; - return $this; - } - - /** - * Setter para o arquivo da classe CoreExt_DataMapper da classe de reference - * informada por setReferenceClass. - * @param string $key - * @param int $value - * @return CoreExt_Entity Provê interface fluída - */ - public function setReferenceFile($key, $file) - { - $this->_references[$key]['file'] = $file; - return $this; - } - - /** - * Getter. - * @param string $key - * @return mixed - */ - protected function _getReferenceValue($key) - { - return isset($this->_references[$key]['value']) ? $this->_references[$key]['value'] : null; - } - - /** - * Getter. - * @param string $key - * @return string - */ - protected function _getReferenceClass($key) - { - return isset($this->_references[$key]['class']) ? $this->_references[$key]['class'] : null; - } - - /** - * Verifica se a classe da referência é uma instância de CoreExt_DataMapper. - * @param string $key - * @return bool - */ - public function _isReferenceDataMapper($key) - { - $class = $this->_getReferenceClass($key); - $reference = isset($this->_references[$key]['file']) ? $this->_references[$key]['file'] : null; - return $this->_isReferenceOf($class, $reference, - 'CoreExt_DataMapper'); - } - - /** - * Verifica se a classe da referência é uma instância de CoreExt_Enum. - * @param string $key - * @return bool - */ - protected function _isReferenceEnum($key) - { - $class = $this->_getReferenceClass($key); - return $this->_isReferenceOf($class, $this->_references[$key]['file'], - 'CoreExt_Enum'); - } - - /** - * Verifica se a referência é subclasse de $parentClass. - * - * @param string $subClass - * @param string $subClassFile - * @param string $parentClass - * @return bool - */ - private function _isReferenceOf($subClass, $subClassFile, $parentClass) - { - static $required = array(); - - if (is_string($subClass)) { - if (!in_array($subClassFile, $required)) { - // Inclui o arquivo com a definição de subclasse para que o interpretador - // tenha o símbolo de comparação. - require_once $subClassFile; - $required[] = $subClassFile; - } - return (is_subclass_of($subClass, $parentClass)); + + /** + * Setter. + * + * @param CoreExt_DataMapper $dataMapper + * + * @return CoreExt_Entity + */ + public function setDataMapper(CoreExt_DataMapper $dataMapper) + { + $this->_dataMapper = $dataMapper; + + return $this; } - return FALSE; - } - - /** - * Setter. - * @param CoreExt_DataMapper $dataMapper - * @return CoreExt_Entity - */ - public function setDataMapper(CoreExt_DataMapper $dataMapper) - { - $this->_dataMapper = $dataMapper; - return $this; - } - - /** - * Getter. - * @return CoreExt_DataMapper|NULL - */ - public function getDataMapper() - { - return $this->_dataMapper; - } - - /** - * Adiciona uma classe para o repositório de classes estático, instanciando - * caso não seja passada uma instância explícita e carregando o arquivo - * em que a classe está armazenada caso seja informado. - * - * Quando uma instância não é passada explicitamente, verifica-se se a - * instância já existe, retornado-a caso positivo e/ou instanciando uma nova - * (sem passar argumentos para seu construtor) e retornando-a. - * - * Permite armazenar apenas uma instância de uma classe por vez. Por usar - * armazenamento estático, pode ter efeitos indesejados ao ser usado por - * diferentes objetos. - * - * Caso seja necessário instanciar a classe passando argumentos ao seu - * construtor, instancie a classe e passe a referencia na chamada ao método: - * - * - * 'value1')); - * CoreExt_Entity::addClassToStorage('CoreExt_Entity', $obj); - * - * - * @param string $class O nome da classe - * @param mixed $instance Uma instância da classe - * @param string $file O nome do arquivo onde se encontra a classe - * @param bool $sticky Se a instância da classe de ser "grundenda", - * não podendo ser posteriormente substituída por uma chamada subsequente - * @return mixed - * @throws CoreExt_Exception_InvalidArgumentException - */ - public static function addClassToStorage($class, $instance = NULL, $file = NULL, $sticky = FALSE) - { - $search = strtolower($class); - if (TRUE === array_key_exists($search, self::$_classStorage)) { - self::_setStorageClassInstance($search, $instance, $sticky); + + /** + * Getter. + * + * @return CoreExt_DataMapper|NULL + */ + public function getDataMapper() + { + return $this->_dataMapper; } - else { - if (!is_null($file)) { - require_once $file; - } - self::$_classStorage[$search] = array( - 'class' => $class, - 'instance' => NULL, - 'sticky' => FALSE - ); - self::_setStorageClassInstance($class, $instance, $sticky); + + /** + * Adiciona uma classe para o repositório de classes estático, instanciando + * caso não seja passada uma instância explícita e carregando o arquivo + * em que a classe está armazenada caso seja informado. + * + * Quando uma instância não é passada explicitamente, verifica-se se a + * instância já existe, retornado-a caso positivo e/ou instanciando uma nova + * (sem passar argumentos para seu construtor) e retornando-a. + * + * Permite armazenar apenas uma instância de uma classe por vez. Por usar + * armazenamento estático, pode ter efeitos indesejados ao ser usado por + * diferentes objetos. + * + * Caso seja necessário instanciar a classe passando argumentos ao seu + * construtor, instancie a classe e passe a referencia na chamada ao método: + * + * + * 'value1')); + * CoreExt_Entity::addClassToStorage('CoreExt_Entity', $obj); + * + * + * @param string $class O nome da classe + * @param mixed $instance Uma instância da classe + * @param string $file O nome do arquivo onde se encontra a classe + * @param bool $sticky Se a instância da classe de ser "grundenda", + * não podendo ser posteriormente substituída por uma chamada subsequente + * + * @return mixed + * + * @throws CoreExt_Exception_InvalidArgumentException + */ + public static function addClassToStorage($class, $instance = null, $file = null, $sticky = false) + { + $search = strtolower($class); + if (true === array_key_exists($search, self::$_classStorage)) { + self::_setStorageClassInstance($search, $instance, $sticky); + } else { + if (!is_null($file)) { + require_once $file; + } + self::$_classStorage[$search] = [ + 'class' => $class, + 'instance' => null, + 'sticky' => false + ]; + self::_setStorageClassInstance($class, $instance, $sticky); + } + + return self::$_classStorage[$search]['instance']; } - return self::$_classStorage[$search]['instance']; - } - - /** - * Instancia uma classe de $class ou atribui uma instância passada - * explicitamente para o repositório de classes estático. - * - * @param string $class - * @param mixed $instance - * @return mixed - * @throws CoreExt_Exception_InvalidArgumentException - */ - protected static function _setStorageClassInstance($class, $instance = NULL, $sticky = FALSE) - { - if (!is_null($instance)) { - if (!($instance instanceof $class)) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException('A instância ' - . 'passada como argumento precisa ser uma instância de "' . $class . '".'); - } - - if (FALSE == self::$_classStorage[strtolower($class)]['sticky']) { - self::$_classStorage[strtolower($class)]['instance'] = $instance; - self::$_classStorage[strtolower($class)]['sticky'] = $sticky; - } - // Se for sticky, só sobrescreve por outro - elseif (TRUE == self::$_classStorage[strtolower($class)]['sticky'] && TRUE == $sticky) { - self::$_classStorage[strtolower($class)]['instance'] = $instance; - self::$_classStorage[strtolower($class)]['sticky'] = $sticky; - } + + /** + * Instancia uma classe de $class ou atribui uma instância passada + * explicitamente para o repositório de classes estático. + * + * @param string $class + * @param mixed $instance + * + * @return mixed + * + * @throws CoreExt_Exception_InvalidArgumentException + */ + protected static function _setStorageClassInstance($class, $instance = null, $sticky = false) + { + if (!is_null($instance)) { + if (!($instance instanceof $class)) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException( + 'A instância ' . 'passada como argumento precisa ser uma instância de "' . $class . '".' + ); + } + + if (false == self::$_classStorage[strtolower($class)]['sticky']) { + self::$_classStorage[strtolower($class)]['instance'] = $instance; + self::$_classStorage[strtolower($class)]['sticky'] = $sticky; + } // Se for sticky, só sobrescreve por outro + elseif (true == self::$_classStorage[strtolower($class)]['sticky'] && true == $sticky) { + self::$_classStorage[strtolower($class)]['instance'] = $instance; + self::$_classStorage[strtolower($class)]['sticky'] = $sticky; + } + } else { + if (is_null(self::$_classStorage[strtolower($class)]['instance'])) { + self::$_classStorage[strtolower($class)]['instance'] = new $class(); + self::$_classStorage[strtolower($class)]['sticky'] = $sticky; + } + } } - else { - if (is_null(self::$_classStorage[strtolower($class)]['instance'])) { - self::$_classStorage[strtolower($class)]['instance'] = new $class(); - self::$_classStorage[strtolower($class)]['sticky'] = $sticky; - } + + /** + * Getter. + * + * @param string $class + * + * @return mixed|NULL + */ + public static function getClassFromStorage($class) + { + if (self::hasClassInStorage($class)) { + return self::$_classStorage[strtolower($class)]['instance']; + } + + return null; } - } - - /** - * Getter. - * @param string $class - * @return mixed|NULL - */ - public static function getClassFromStorage($class) - { - if (self::hasClassInStorage($class)) { - return self::$_classStorage[strtolower($class)]['instance']; + + /** + * Verifica se uma classe existe no repositório de classes estático. + * + * @param string $class + * + * @return bool + */ + public static function hasClassInStorage($class) + { + if (array_key_exists(strtolower($class), self::$_classStorage)) { + return true; + } + + return false; } - return NULL; - } - - /** - * Verifica se uma classe existe no repositório de classes estático. - * @param string $class - * @return bool - */ - public static function hasClassInStorage($class) - { - if (array_key_exists(strtolower($class), self::$_classStorage)) { - return TRUE; + + /** + * Setter. + * + * @param CoreExt_Locale $instance + * + * @return CoreExt_Entity + */ + public function setLocale(CoreExt_Locale $instance) + { + $this->_locale = $instance; + + return $this; } - return FALSE; - } - - /** - * Setter. - * @param CoreExt_Locale $instance - * @return CoreExt_DataMapper Provê interface fluída - */ - public function setLocale(CoreExt_Locale $instance) - { - $this->_locale = $instance; - return $this; - } - - /** - * Getter. - * @return CoreExt_Locale - */ - public function getLocale() - { - if (is_null($this->_locale)) { - require_once 'CoreExt/Locale.php'; - $this->setLocale(CoreExt_Locale::getInstance()); + + /** + * Getter. + * + * @return CoreExt_Locale + */ + public function getLocale() + { + if (is_null($this->_locale)) { + require_once 'CoreExt/Locale.php'; + $this->setLocale(CoreExt_Locale::getInstance()); + } + + return $this->_locale; } - return $this->_locale; - } - - /** - * Verifica se a propriedade informada por $key é válida, executando o - * CoreExt_Validate_Interface relacionado. - * - * Utiliza lazy initialization para inicializar os validadores somente quando - * necessário. - * - * @link http://martinfowler.com/eaaCatalog/lazyLoad.html Lazy initialization - * @param string $key Propriedade a ser validade. Caso seja string vazia, - * executa todos os validadores da instância - * @return bool - * @see CoreExt_Validate_Validatable#isValid($key) - */ - public function isValid($key = '') - { - $this->_setDefaultValidatorCollection() - ->_setDefaultErrorCollectionItems(); - - $key = trim($key); - $return = NULL; - - if ('' != $key && !is_null($this->getValidator($key))) { - $return = $this->_isValidProperty($key); + + /** + * Verifica se a propriedade informada por $key é válida, executando o + * CoreExt_Validate_Interface relacionado. + * + * Utiliza lazy initialization para inicializar os validadores somente quando + * necessário. + * + * @link http://martinfowler.com/eaaCatalog/lazyLoad.html Lazy initialization + * + * @param string $key Propriedade a ser validade. Caso seja string vazia, + * executa todos os validadores da instância + * + * @return bool + * + * @see CoreExt_Validate_Validatable#isValid($key) + */ + public function isValid($key = '') + { + $this->_setDefaultValidatorCollection() + ->_setDefaultErrorCollectionItems(); + + $key = trim($key); + $return = null; + + if ('' != $key && !is_null($this->getValidator($key))) { + $return = $this->_isValidProperty($key); + } elseif ('' === $key) { + $return = $this->_isValidEntity(); + } + + return $return; } - elseif ('' === $key) { - $return = $this->_isValidEntity(); + + /** + * Verifica se uma instância é nula, isto é, quando todos os seus atributos + * tem o valor NULL. + * + * @return bool + */ + public function isNull() + { + $data = $this->toDataArray(); + $count = count($this->_data); + $nils = 0; + + foreach ($data as $value) { + if (is_null($value)) { + $nils++; + } + } + + if ($nils == $count) { + return true; + } + + return false; } - return $return; - } - - /** - * Verifica se uma instância é nula, isto é, quando todos os seus atributos - * tem o valor NULL. - * - * @return bool - */ - public function isNull() - { - $data = $this->toDataArray(); - $count = count($this->_data); - $nils = 0; - - foreach ($data as $value) { - if (is_null($value)) { - $nils++; - } + /** + * Alias para setNew(FALSE). + * + * @return CoreExt_Entity Provê interface fluída + */ + public function markOld() + { + return $this->setNew(false); } - if ($nils == $count) { - return TRUE; + /** + * Setter. + * + * @param bool $new + * + * @return CoreExt_Entity Provê interface fluída + */ + public function setNew($new) + { + $this->_new = (bool) $new; + + return $this; } - return FALSE; - } - - /** - * Alias para setNew(FALSE). - * @return CoreExt_Entity Provê interface fluída - */ - public function markOld() - { - return $this->setNew(FALSE); - } - - /** - * Setter. - * @param bool $new - * @return CoreExt_Entity Provê interface fluída - */ - public function setNew($new) - { - $this->_new = (bool) $new; - return $this; - } - - /** - * Verifica se a instância é "nova". - * @return bool - * @see CoreExt_Entity#_new - */ - public function isNew() - { - return $this->_new; - } - - /** - * Verifica se uma propriedade da classe é válida de acordo com um validador - * CoreExt_Validate_Interface. - * - * Utiliza o valor sanitizado pelo validador como valor de atributo. - * - * @param string $key - * @return bool - */ - protected function _isValidProperty($key) - { - try { - $this->getValidator($key)->isValid($this->get($key)); - $this->$key = $this->getValidator($key)->getSanitizedValue(); - return TRUE; + /** + * Verifica se a instância é "nova". + * + * @return bool + * + * @see CoreExt_Entity#_new + */ + public function isNew() + { + return $this->_new; } - catch (Exception $e) { - $this->_setError($key, $e->getMessage()); - return FALSE; + + /** + * Verifica se uma propriedade da classe é válida de acordo com um validador + * CoreExt_Validate_Interface. + * + * Utiliza o valor sanitizado pelo validador como valor de atributo. + * + * @param string $key + * + * @return bool + */ + protected function _isValidProperty($key) + { + try { + $this->getValidator($key)->isValid($this->get($key)); + $this->$key = $this->getValidator($key)->getSanitizedValue(); + + return true; + } catch (Exception $e) { + $this->_setError($key, $e->getMessage()); + + return false; + } } - } - - /** - * Verifica se todas as propriedades da classe são válida de acordo com uma - * coleção de validadores CoreExt_Validate_Interface. - * - * @return bool - */ - protected function _isValidEntity() - { - $return = TRUE; - - // Como eu quero todos os erros de validação, apenas marco $return como - // FALSE e deixo o iterador exaurir. - foreach ($this->getValidatorCollection() as $key => $validator) { - if (FALSE === $this->_isValidProperty($key)) { - $return = FALSE; - } + + /** + * Verifica se todas as propriedades da classe são válida de acordo com uma + * coleção de validadores CoreExt_Validate_Interface. + * + * @return bool + */ + protected function _isValidEntity() + { + $return = true; + + // Como eu quero todos os erros de validação, apenas marco $return como + // FALSE e deixo o iterador exaurir. + foreach ($this->getValidatorCollection() as $key => $validator) { + if (false === $this->_isValidProperty($key)) { + $return = false; + } + } + + return $return; } - return $return; - } + /** + * @see CoreExt_Validate_Validatable#setValidator($key, $validator) + */ + public function setValidator($key, CoreExt_Validate_Interface $validator) + { + if (!array_key_exists($key, $this->_data)) { + throw new Exception('A propriedade ' . $key . ' não existe em ' . __CLASS__ . '.'); + } + + $this->_validators[$key] = $validator; + $this->_setError($key, null); - /** - * @see CoreExt_Validate_Validatable#setValidator($key, $validator) - */ - public function setValidator($key, CoreExt_Validate_Interface $validator) - { - if (!array_key_exists($key, $this->_data)) { - throw new Exception('A propriedade ' . $key . ' não existe em ' . __CLASS__ . '.'); + return $this; } - $this->_validators[$key] = $validator; - $this->_setError($key, NULL); - return $this; - } + /** + * @see CoreExt_Validate_Validatable#getValidator($key) + */ + public function getValidator($key) + { + $return = null; - /** - * @see CoreExt_Validate_Validatable#getValidator($key) - */ - public function getValidator($key) - { - $return = NULL; + if (isset($this->_validators[$key])) { + $return = $this->_validators[$key]; + } - if (isset($this->_validators[$key])) { - $return = $this->_validators[$key]; + return $return; } - return $return; - } - - /** - * @param $overwrite TRUE para que as novas instâncias sobrescrevam as já - * existentes - * @see CoreExt_Entity_Validatable#setValidatorCollection($validators) - */ - public function setValidatorCollection(array $validators, $overwrite = FALSE) - { - foreach ($validators as $key => $validator) { - if ($overwrite == FALSE && !is_null($this->getValidator($key))) { - continue; - } - $this->setValidator($key, $validator); + /** + * @see CoreExt_Entity_Validatable::setValidatorCollection() + * + * @param array $validators + * @param $overwrite TRUE para que as novas instâncias sobrescrevam as já existentes + * + * @return CoreExt_Entity + * + * @throws Exception + * + */ + public function setValidatorCollection(array $validators, $overwrite = false) + { + foreach ($validators as $key => $validator) { + if ($overwrite == false && !is_null($this->getValidator($key))) { + continue; + } + + $this->setValidator($key, $validator); + } + + return $this; } - return $this; - } - - /** - * @see CoreExt_Entity_Validatable#getValidatorCollection() - */ - public function getValidatorCollection() - { - $this->_setDefaultValidatorCollection(); - return $this->_validators; - } - - /** - * Configura os validadores padrão da classe. - * @return CoreExt_Entity Provê interface fluída - */ - protected function _setDefaultValidatorCollection() - { - $this->setValidatorCollection($this->getDefaultValidatorCollection()); - return $this; - } - - /** - * Retorna um instância de um validador caso um atributo da instância tenha - * seu valor igual ao da condição. - * - * @param string $key O atributo a ser comparado - * @param mixed $value O valor para comparação - * @param string $validatorClassName O nome da classe de validação. Deve ser - * subclasse de CoreExt_Validate_Abstract - * @param array $equalsParams Array de opções para o a classe de - * validação caso de $key ser igual a $value - * @param array $notEqualsParams Array de opções para o a classe de - * validação caso de $key ser diferente de $value - * @return CoreExt_Validate_Abstract - * @throws CoreExt_Exception_InvalidArgumentException - */ - public function validateIfEquals($key, $value = NULL, $validatorClassName, - array $equalsParams = array(), array $notEqualsParams = array()) - { - if ($value == $this->get($key)) { - $params = $equalsParams; + + /** + * @see CoreExt_Entity_Validatable#getValidatorCollection() + */ + public function getValidatorCollection() + { + $this->_setDefaultValidatorCollection(); + + return $this->_validators; } - else { - $params = $notEqualsParams; + + /** + * Configura os validadores padrão da classe. + * + * @return CoreExt_Entity + * + * @throws Exception + */ + protected function _setDefaultValidatorCollection() + { + $this->setValidatorCollection($this->getDefaultValidatorCollection()); + + return $this; } - if (!is_subclass_of($validatorClassName, 'CoreExt_Validate_Abstract')) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException('A classe "' + /** + * Retorna um instância de um validador caso um atributo da instância tenha + * seu valor igual ao da condição. + * + * @param string $key O atributo a ser comparado + * @param mixed $value O valor para comparação + * @param string $validatorClassName O nome da classe de validação. Deve ser + * subclasse de CoreExt_Validate_Abstract + * @param array $equalsParams Array de opções para o a classe de + * validação caso de $key ser igual a $value + * @param array $notEqualsParams Array de opções para o a classe de + * validação caso de $key ser diferente de $value + * + * @return CoreExt_Validate_Abstract + * + * @throws CoreExt_Exception_InvalidArgumentException + */ + public function validateIfEquals( + $key, + $value = null, + $validatorClassName, + array $equalsParams = [], + array $notEqualsParams = [] + ) { + if ($value == $this->get($key)) { + $params = $equalsParams; + } else { + $params = $notEqualsParams; + } + + if (!is_subclass_of($validatorClassName, 'CoreExt_Validate_Abstract')) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException( + 'A classe "' . $validatorClassName . '" não é uma subclasse de CoreExt_Validate_Abstract' - . ' e por isso não pode ser usada como classe de validação.'); - } + . ' e por isso não pode ser usada como classe de validação.' + ); + } - return new $validatorClassName($params); - } - - /** - * Configura uma mensagem de erro. - * - * @param string $key - * @param string|NULL $message - * @return CoreExt_Entity Provê interface fluída - */ - protected function _setError($key, $message = NULL) - { - $this->_errors[$key] = $message; - return $this; - } - - /** - * Retorna uma mensagem de erro de validaçao para determinada propriedade. - * - * @param string $key - * @return mixed - */ - public function getError($key) - { - return $this->_errors[$key]; - } - - /** - * Retorna um array de mensagens de erro de validação. - * @return array - */ - public function getErrors() - { - return $this->_errors; - } - - /** - * Verifica se uma propriedade tem um erro de validação. - * - * @param string $key - * @return bool - */ - public function hasError($key) - { - if (!is_null($this->getError($key))) { - return TRUE; + return new $validatorClassName($params); } - return FALSE; - } - - /** - * Verifica se houve algum erro de validação geral. - * @return bool - */ - public function hasErrors() - { - foreach ($this->getErrors() as $key => $error) { - if ($this->hasError($key)) { - return TRUE; - } + + /** + * Configura uma mensagem de erro. + * + * @param string $key + * @param string|NULL $message + * + * @return CoreExt_Entity Provê interface fluída + */ + protected function _setError($key, $message = null) + { + $this->_errors[$key] = $message; + + return $this; } - return FALSE; - } - - /** - * Configura os itens padrão do array de erros. - * @return CoreExt_Entity Provê interface fluída - */ - protected function _setDefaultErrorCollectionItems() - { - $items = array_keys($this->getValidatorCollection()); - $this->_errors = array_fill_keys($items, NULL); - return $this; - } - - /** - * Retorna o valor de uma propriedade do objeto convertida para o seu tipo - * qual definido pelo array $_dataTypes. - * - * Atualmente suporte os tipos: - * - boolean (informado como bool ou boolean) - * - numeric (converte para número, usando informação do locale atual e - * convertendo para número com {@link http://br.php.net/floatval floatval())} - * - * - * NULL); - * protected $_dataTypes = array('hasChild' => 'bool'); - * } - * - * - * @param string $key O nome da propriedade - * @param mixed $val O valor original da propriedade - * @return mixed O valor convertido da propriedade - */ - protected function _getValue($key, $val) - { - if (!array_key_exists($key, $this->_dataTypes)) { - // Converte com floatval (que converte para int caso não tenha decimais, - // para permitir formatação correta com o locale da aplicação) - if (is_numeric($val)) { - $val = floatval($val); - } - return $val; + + /** + * Retorna uma mensagem de erro de validaçao para determinada propriedade. + * + * @param string $key + * + * @return mixed + */ + public function getError($key) + { + return $this->_errors[$key]; } - $cmpVal = strtolower($val); - $return = NULL; + /** + * Retorna um array de mensagens de erro de validação. + * + * @return array + */ + public function getErrors() + { + return $this->_errors; + } - switch (strtolower($this->_dataTypes[$key])) { - case 'bool': - case 'boolean': - if ($cmpVal == 't') { - $return = TRUE; + /** + * Verifica se uma propriedade tem um erro de validação. + * + * @param string $key + * + * @return bool + */ + public function hasError($key) + { + if (!is_null($this->getError($key))) { + return true; } - elseif ($cmpVal == 'f') { - $return = FALSE; - } - else { - $return = (bool) $cmpVal; - } - break; - case 'numeric': - $return = $this->getFloat($cmpVal); - break; + return false; + } - case 'string': - $return = (string)$cmpVal; - break; + /** + * Verifica se houve algum erro de validação geral. + * + * @return bool + */ + public function hasErrors() + { + foreach ($this->getErrors() as $key => $error) { + if ($this->hasError($key)) { + return true; + } + } + + return false; } - return $return; - } - - /** - * Retorna um número float, verificando o locale e substituindo o separador - * decimal pelo separador compatível com o separador padrão do PHP ("." ponto). - * - * @param numeric $value - * @return float - */ - public function getFloat($value) - { - $locale = $this->getLocale(); - $decimalPoint = $locale->getCultureInfo('decimal_point'); - - // Verifica se possui o ponto decimal do locale e substitui para o - // padrão do locale en_US (ponto ".") - if (FALSE !== strstr($value, $decimalPoint)) { - $value = strtr($value, $decimalPoint, '.'); + + /** + * Configura os itens padrão do array de erros. + * + * @return CoreExt_Entity Provê interface fluída + */ + protected function _setDefaultErrorCollectionItems() + { + $items = array_keys($this->getValidatorCollection()); + $this->_errors = array_fill_keys($items, null); + + return $this; } - return floatval($value); - } - - /** - * Retorna um array onde o índice é o valor do atributo $atr1 e o valor - * é o próprio valor do atributo referenciado por $atr2. Se $atr2 não for - * informado, retorna o valor referenciado por $atr1. - * - * Exemplo: - * - * NULL, - * 'sobrenome' => NULL - * ); - * - * // em um script: - * $pessoa = new Pessoa(array('id' => 1, 'nome' => 'Carlos Santana')); - * print_r($pessoa->filterAttr('id' => 'nome'); - * - * // Iria imprimir: - * // Array - * // ( - * // [1] => Carlos Santana - * // ) - * - * - * @param string $atr1 - * @param string $atr2 - * @return array - */ - public function filterAttr($atr1, $atr2 = '') - { - $data = array(); - - if ('' == $atr2) { - $atr2 = $atr1; + /** + * Retorna o valor de uma propriedade do objeto convertida para o seu tipo + * qual definido pelo array $_dataTypes. + * + * Atualmente suporte os tipos: + * - boolean (informado como bool ou boolean) + * - numeric (converte para número, usando informação do locale atual e + * convertendo para número com {@link http://br.php.net/floatval floatval())} + * + * + * NULL); + * protected $_dataTypes = array('hasChild' => 'bool'); + * } + * + * + * @param string $key O nome da propriedade + * @param mixed $val O valor original da propriedade + * + * @return mixed O valor convertido da propriedade + */ + protected function _getValue($key, $val) + { + if (!array_key_exists($key, $this->_dataTypes)) { + // Converte com floatval (que converte para int caso não tenha decimais, + // para permitir formatação correta com o locale da aplicação) + if (is_numeric($val)) { + $val = floatval($val); + } + + return $val; + } + + $cmpVal = strtolower($val); + $return = null; + + switch (strtolower($this->_dataTypes[$key])) { + case 'bool': + case 'boolean': + if ($cmpVal == 't') { + $return = true; + } elseif ($cmpVal == 'f') { + $return = false; + } else { + $return = (bool) $cmpVal; + } + break; + + case 'numeric': + $return = $this->getFloat($cmpVal); + break; + + case 'string': + $return = (string) $cmpVal; + break; + } + + return $return; } - $data[$this->$atr1] = $this->$atr2; - return $data; - } - - /** - * Retorna um array para cada instância de CoreExt_Entity, onde cada entrada - * é um array onde o índice é o valor do atributo $atr1 e o valor - * é o próprio valor do atributo referenciado por $atr2. Se $atr2 não for - * informado, retorna o valor referenciado por $atr1. - * - * @param CoreExt_Entity|array $instance - * @param string $atr1 - * @param string $atr2 - * @return array - * @see CoreExt_Entity#filterAttr($atr1, $atr2) - */ - public static function entityFilterAttr($instance, $atr1, $atr2 = '') - { - $instances = $data = array(); - - if (!is_array($instance)) { - $instances[] = $instance; + /** + * Retorna um número float, verificando o locale e substituindo o separador + * decimal pelo separador compatível com o separador padrão do PHP ("." ponto). + * + * @param string $value + * + * @return float + */ + public function getFloat($value) + { + $locale = $this->getLocale(); + $decimalPoint = $locale->getCultureInfo('decimal_point'); + + // Verifica se possui o ponto decimal do locale e substitui para o + // padrão do locale en_US (ponto ".") + if (false !== strstr($value, $decimalPoint)) { + $value = strtr($value, $decimalPoint, '.'); + } + + return floatval($value); } - else { - $instances = $instance; + + /** + * Retorna um array onde o índice é o valor do atributo $atr1 e o valor + * é o próprio valor do atributo referenciado por $atr2. Se $atr2 não for + * informado, retorna o valor referenciado por $atr1. + * + * Exemplo: + * + * NULL, + * 'sobrenome' => NULL + * ); + * + * // em um script: + * $pessoa = new Pessoa(array('id' => 1, 'nome' => 'Carlos Santana')); + * print_r($pessoa->filterAttr('id' => 'nome'); + * + * // Iria imprimir: + * // Array + * // ( + * // [1] => Carlos Santana + * // ) + * + * + * @param string $atr1 + * @param string $atr2 + * + * @return array + */ + public function filterAttr($atr1, $atr2 = '') + { + $data = []; + + if ('' == $atr2) { + $atr2 = $atr1; + } + + $data[$this->$atr1] = $this->$atr2; + + return $data; } - foreach ($instances as $instance) { - $arr = $instance->filterAttr($atr1, $atr2); - $key = key($arr); - $data[$key] = $arr[$key]; + /** + * Retorna um array para cada instância de CoreExt_Entity, onde cada entrada + * é um array onde o índice é o valor do atributo $atr1 e o valor + * é o próprio valor do atributo referenciado por $atr2. Se $atr2 não for + * informado, retorna o valor referenciado por $atr1. + * + * @param CoreExt_Entity|array $instance + * @param string $atr1 + * @param string $atr2 + * + * @return array + * + * @see CoreExt_Entity#filterAttr($atr1, $atr2) + */ + public static function entityFilterAttr($instance, $atr1, $atr2 = '') + { + $instances = $data = []; + + if (!is_array($instance)) { + $instances[] = $instance; + } else { + $instances = $instance; + } + + foreach ($instances as $instance) { + $arr = $instance->filterAttr($atr1, $atr2); + $key = key($arr); + $data[$key] = $arr[$key]; + } + + return $data; } - return $data; - } - - /** - * Retorna o estado (valores dos atributos) da instância em array. Se um - * atributo for uma referência a um objeto, faz o lazy load do mesmo. - * @return array - */ - public function toArray() - { - $data = array(); - foreach ($this->_data as $key => $val) { - $data[$key] = $this->$key; + /** + * Retorna o estado (valores dos atributos) da instância em array. Se um + * atributo for uma referência a um objeto, faz o lazy load do mesmo. + * + * @return array + */ + public function toArray() + { + $data = []; + + foreach ($this->_data as $key => $val) { + $data[$key] = $this->$key; + } + + return $data; } - return $data; - } - - /** - * Retorna o estado (valores dos atributos) da instância. Se um atributo - * for uma referência a um objeto, retorna o valor da referência. - * @return array - */ - public function toDataArray() - { - $data = array(); - foreach ($this->_data as $key => $value) { - if ($this->_hasReference($key)) { - $data[$key] = $this->_references[$key]['value']; - continue; - } - $data[$key] = $value; + + /** + * Retorna o estado (valores dos atributos) da instância. Se um atributo + * for uma referência a um objeto, retorna o valor da referência. + * + * @return array + */ + public function toDataArray() + { + $data = []; + foreach ($this->_data as $key => $value) { + if ($this->_hasReference($key)) { + $data[$key] = $this->_references[$key]['value']; + continue; + } + $data[$key] = $value; + } + + return $data; } - return $data; - } } diff --git a/ieducar/lib/CoreExt/Entity/Validatable.php b/ieducar/lib/CoreExt/Entity/Validatable.php index f125758751..296b8f25ca 100644 --- a/ieducar/lib/CoreExt/Entity/Validatable.php +++ b/ieducar/lib/CoreExt/Entity/Validatable.php @@ -1,77 +1,41 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Entity - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Validatable.php'; -/** - * CoreExt_Entity_Validatable interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Entity - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Entity_Validatable extends CoreExt_Validate_Validatable { - /** - * Configura uma coleção de CoreExt_Validate_Interface na instância. - * @return CoreExt_Entity Provê interface fluída - */ - public function setValidatorCollection(array $validators); + /** + * Configura uma coleção de CoreExt_Validate_Interface na instância. + * + * @return CoreExt_Entity Provê interface fluída + */ + public function setValidatorCollection(array $validators); - /** - * Retorna um array de itens CoreExt_Validate_Interface da instância. - * @return array - */ - public function getValidatorCollection(); + /** + * Retorna um array de itens CoreExt_Validate_Interface da instância. + * + * @return array + */ + public function getValidatorCollection(); - /** - * Retorna um array de CoreExt_Validate_Interface padrão para as propriedades - * de CoreExt_Entity. - * - * Cada item do array precisa ser um item associativo com o mesmo nome do - * atributo público definido pelo array $_data: - * - * - * new CoreExt_Validate_Alpha(), - * 'telefone' => new CoreExt_Validate_Alphanum() - * ); - * - * - * @return array - */ - public function getDefaultValidatorCollection(); -} \ No newline at end of file + /** + * Retorna um array de CoreExt_Validate_Interface padrão para as propriedades + * de CoreExt_Entity. + * + * Cada item do array precisa ser um item associativo com o mesmo nome do + * atributo público definido pelo array $_data: + * + * + * new CoreExt_Validate_Alpha(), + * 'telefone' => new CoreExt_Validate_Alphanum() + * ); + * + * + * @return array + */ + public function getDefaultValidatorCollection(); +} diff --git a/ieducar/lib/CoreExt/Enum.php b/ieducar/lib/CoreExt/Enum.php index f94524691d..ee831cbde0 100644 --- a/ieducar/lib/CoreExt/Enum.php +++ b/ieducar/lib/CoreExt/Enum.php @@ -1,171 +1,126 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Enum - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Singleton.php'; -/** - * CoreExt_Enum abstract class. - * - * Provê uma interface simples de criação de instâncias semelhantes a um - * Enum do Java. - * - * As semelhanças são poucas mas a intenção é a de dar uma forma direta de - * criar tipos enumerados. Para isso, basta subclassificar essa classe e prover - * valores para o array $_data. Adicionalmente, prover constantes que ajudaram - * ao usuario da classe a facilmente acessar os valores dos enumerados é uma - * sugestão. - * - * O stub de teste CoreExt_Enum1Stub é um exemplo de como criar tipos - * enumerados. - * - * Essa classe implementa também a interface ArrayAccess de SPL, provendo acesso - * fácil aos valores do enumerado em uma forma de array: - * - * - * - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @link http://br2.php.net/manual/en/class.arrayaccess.php ArrayAccess interface - * @package CoreExt_Singleton - * @since Classe disponível desde a versão 1.1.0 - * @todo Verificar se é substituível pela implementação de Enum disponível - * em spl_types do Pecl {@link http://www.php.net/manual/en/splenum.construct.php SplEnum}. - * @version @@package_version@@ - */ abstract class CoreExt_Enum extends CoreExt_Singleton implements ArrayAccess { - /** - * Array que emula um enum. - * @var array - */ - protected $_data = array(); + /** + * Array que emula um enum. + * + * @var array + */ + protected $_data = []; - /** - * Retorna o valor para um dado índice de CoreExt_Enum. - * @param string|int $key - * @return mixed - */ - public function getValue($key) - { - return $this->_data[$key]; - } + /** + * Retorna o valor para um dado índice de CoreExt_Enum. + * + * @param string|int $key + * + * @return mixed + */ + public function getValue($key) + { + return $this->_data[$key]; + } - /** - * Retorna todos os valores de CoreExt_Enum. - * @return array - */ - public function getValues() - { - return array_values($this->_data); - } + /** + * Retorna todos os valores de CoreExt_Enum. + * + * @return array + */ + public function getValues() + { + return array_values($this->_data); + } - /** - * Retorna o valor da índice para um determinado valor. - * @param mixed $value - * @return int|string - */ - public function getKey($value) - { - return array_search($value, $this->_data); - } + /** + * Retorna o valor da índice para um determinado valor. + * + * @param mixed $value + * + * @return int|string + */ + public function getKey($value) + { + return array_search($value, $this->_data); + } - /** - * Retorna todos os índices de CoreExt_Enum. - * @return array - */ - public function getKeys() - { - return array_keys($this->_data); - } + /** + * Retorna todos os índices de CoreExt_Enum. + * + * @return array + */ + public function getKeys() + { + return array_keys($this->_data); + } - /** - * Retorna o array de enums. - * @return array - */ - public function getEnums() - { - return $this->_data; - } + /** + * Retorna o array de enums. + * + * @return array + */ + public function getEnums() + { + return $this->_data; + } - /** - * Implementa offsetExists da interface ArrayAccess. - * @link http://br2.php.net/manual/en/arrayaccess.offsetexists.php - * @param string|int $offset - * @return bool - */ - public function offsetExists($offset) - { - return isset($this->_data[$offset]); - } + /** + * Implementa offsetExists da interface ArrayAccess. + * + * @link http://br2.php.net/manual/en/arrayaccess.offsetexists.php + * + * @param string|int $offset + * + * @return bool + */ + public function offsetExists($offset) + { + return isset($this->_data[$offset]); + } - /** - * Implementa offsetUnset da interface ArrayAccess. - * @link http://br2.php.net/manual/en/arrayaccess.offsetunset.php - * @throws CoreExt_Exception - */ - public function offsetUnset($offset) - { - require_once 'CoreExt/Exception.php'; - throw new CoreExt_Exception('Um "' . get_class($this) . '" é um objeto read-only.'); - } + /** + * Implementa offsetUnset da interface ArrayAccess. + * + * @link http://br2.php.net/manual/en/arrayaccess.offsetunset.php + * + * @throws CoreExt_Exception + */ + public function offsetUnset($offset) + { + require_once 'CoreExt/Exception.php'; + throw new CoreExt_Exception('Um "' . get_class($this) . '" é um objeto read-only.'); + } - /** - * Implementa offsetSet da interface ArrayAccess. - * - * Uma objeto CoreExt_Enum é apenas leitura. - * - * @link http://br2.php.net/manual/en/arrayaccess.offsetset.php - * @param string|int $offset - * @param mixed $value - * @throws CoreExt_Exception - */ - public function offsetSet($offset, $value) - { - require_once 'CoreExt/Exception.php'; - throw new CoreExt_Exception('Um "' . get_class($this) . '" é um objeto read-only.'); - } + /** + * Implementa offsetSet da interface ArrayAccess. + * + * Uma objeto CoreExt_Enum é apenas leitura. + * + * @link http://br2.php.net/manual/en/arrayaccess.offsetset.php + * + * @param string|int $offset + * @param mixed $value + * + * @throws CoreExt_Exception + */ + public function offsetSet($offset, $value) + { + require_once 'CoreExt/Exception.php'; + throw new CoreExt_Exception('Um "' . get_class($this) . '" é um objeto read-only.'); + } - /** - * Implementa offsetGet da interface ArrayAccess. - * - * @link http://br2.php.net/manual/en/arrayaccess.offsetget.php - * @param string|int $offset - * @return mixed - */ - public function offsetGet($offset) - { - return $this->_data[$offset]; - } + /** + * Implementa offsetGet da interface ArrayAccess. + * + * @link http://br2.php.net/manual/en/arrayaccess.offsetget.php + * + * @param string|int $offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return $this->_data[$offset]; + } } diff --git a/ieducar/lib/CoreExt/Exception.php b/ieducar/lib/CoreExt/Exception.php index af6819326b..e96a5cfb58 100644 --- a/ieducar/lib/CoreExt/Exception.php +++ b/ieducar/lib/CoreExt/Exception.php @@ -1,43 +1,5 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Exception - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * CoreExt_Exception class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Exception - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Exception extends Exception { -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Exception/FileNotFoundException.php b/ieducar/lib/CoreExt/Exception/FileNotFoundException.php index 84d19d351b..000f259808 100644 --- a/ieducar/lib/CoreExt/Exception/FileNotFoundException.php +++ b/ieducar/lib/CoreExt/Exception/FileNotFoundException.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Exception - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Exception.php'; -/** - * CoreExt_Exception_FileNotFoundException class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Exception - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Exception_FileNotFoundException extends CoreExt_Exception { -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Exception/InvalidArgumentException.php b/ieducar/lib/CoreExt/Exception/InvalidArgumentException.php index 76e5b4c0c8..f0b7199d68 100644 --- a/ieducar/lib/CoreExt/Exception/InvalidArgumentException.php +++ b/ieducar/lib/CoreExt/Exception/InvalidArgumentException.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Exception - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Exception.php'; -/** - * CoreExt_Exception_InvalidArgumentException class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Exception - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Exception_InvalidArgumentException extends InvalidArgumentException { } diff --git a/ieducar/lib/CoreExt/Service/Exception.php b/ieducar/lib/CoreExt/Service/Exception.php index 946c733e99..dec57c2fc1 100644 --- a/ieducar/lib/CoreExt/Service/Exception.php +++ b/ieducar/lib/CoreExt/Service/Exception.php @@ -4,4 +4,4 @@ class CoreExt_Service_Exception extends CoreExt_Exception { -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Session.php b/ieducar/lib/CoreExt/Session.php index 31670203e2..b6b328ec25 100644 --- a/ieducar/lib/CoreExt/Session.php +++ b/ieducar/lib/CoreExt/Session.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Session/Abstract.php'; -/** - * CoreExt_Session class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Session extends CoreExt_Session_Abstract { -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Session/Abstract.php b/ieducar/lib/CoreExt/Session/Abstract.php index 3ded58c29b..9cfa2df8ed 100644 --- a/ieducar/lib/CoreExt/Session/Abstract.php +++ b/ieducar/lib/CoreExt/Session/Abstract.php @@ -1,352 +1,296 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Configurable.php'; -/** - * CoreExt_Session_Abstract abstract class. - * - * Componente de gerenciamento de session PHP. Implementa as interfaces - * ArrayAccess, Countable e Iterator do Standard PHP Library (SPL), tornando - * possível o acesso simples aos dados da sessão através da interface array - * ou orientada a objeto. - * - * A persistência da session é implementada por uma classe adapter, uma - * subclasse de CoreExt_Session_Storage_Interface. Isso torna simples a - * reposição do storage de session: basta criar um novo adapter e passar como - * argumento ao construtor dessa classe. - * - * As opções de configuração da classe são: - * - sessionStorage: instância de CoreExt_Session_Storage_Interface - * - session_auto_start: bool, se é para iniciar automaticamente a session - * - * Como mencionado, esta classe possui diversas formas de acesso aos dados - * persistidos na session: - * - * - * foo = 'bar'; - * $session->bar = 'foo'; - * - * // Acesso array dos dados da session - * $session->foo2 = 'bar2'; - * $session->bar2 = 'foo2'; - * - * // É possível iterar o objeto CoreExt_Session - * foreach ($session as $key => $value) { - * print $key . ': ' . $value . PHP_EOL; - * } - * - * // Imprime: - * // foo: bar - * // bar: foo - * // foo2: bar2 - * // bar2: foo2 - * - * - * A classe se encarrega de fechar a sessão no final da execução do PHP. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Classe disponível desde a versão 1.1.0 - * @todo Implementar chamada a regenerateId de CoreExt_Session_Storage_Interface - * @todo Implementar funcionalidade "remeber me" - * @version @@package_version@@ - */ -abstract class CoreExt_Session_Abstract - implements CoreExt_Configurable, ArrayAccess, Countable, Iterator +abstract class CoreExt_Session_Abstract implements CoreExt_Configurable, ArrayAccess, Countable, Iterator { - /** - * Opções de configuração geral da classe. - * @var array - */ - protected $_options = array( - 'sessionstorage' => NULL, - 'session_auto_start' => TRUE - ); - - /** - * @var CoreExt_Session_Storage_Interface - */ - protected $_sessionStorage = NULL; - - /** - * @var array - */ - protected $_sessionData = array(); - - /** - * Construtor. - * @param array $options - */ - public function __construct(array $options = array()) - { - $this->setOptions($options); - } - - /** - * @see CoreExt_Configurable#setOptions($options) - */ - public function setOptions(array $options = array()) - { - $options = array_change_key_case($options, CASE_LOWER); - - $defaultOptions = array_keys($this->getOptions()); - $passedOptions = array_keys($options); - - if (0 < count(array_diff($passedOptions, $defaultOptions))) { - require_once 'CoreExt/Exception/InvalidArgumentException.php'; - throw new CoreExt_Exception_InvalidArgumentException( - sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) - ); + /** + * Opções de configuração geral da classe. + * + * @var array + */ + protected $_options = [ + 'sessionstorage' => null, + 'session_auto_start' => true + ]; + + /** + * @var CoreExt_Session_Storage_Interface + */ + protected $_sessionStorage = null; + + /** + * @var array + */ + protected $_sessionData = []; + + /** + * Construtor. + * + * @param array $options + */ + public function __construct(array $options = []) + { + $this->setOptions($options); + } + + /** + * @see CoreExt_Configurable#setOptions($options) + */ + public function setOptions(array $options = []) + { + $options = array_change_key_case($options, CASE_LOWER); + + $defaultOptions = array_keys($this->getOptions()); + $passedOptions = array_keys($options); + + if (0 < count(array_diff($passedOptions, $defaultOptions))) { + require_once 'CoreExt/Exception/InvalidArgumentException.php'; + throw new CoreExt_Exception_InvalidArgumentException( + sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) + ); + } + + if (isset($options['sessionstorage'])) { + $this->setSessionStorage($options['sessionstorage']); + } + + $this->_options = array_merge($this->getOptions(), $options); + + return $this; + } + + /** + * @see CoreExt_Configurable#getOptions() + */ + public function getOptions() + { + return $this->_options; + } + + /** + * Verifica se uma opção está setada. + * + * @param string $key + * + * @return bool + */ + protected function _hasOption($key) + { + return array_key_exists($key, $this->_options); + } + + /** + * Retorna um valor de opção de configuração ou NULL caso a opção não esteja + * setada. + * + * @param string $key + * + * @return mixed|NULL + */ + public function getOption($key) + { + return $this->_hasOption($key) ? $this->_options[$key] : null; + } + + /** + * Setter. + * + * @param CoreExt_Session_Storage_Interface $storage + */ + public function setSessionStorage(CoreExt_Session_Storage_Interface $storage) + { + $this->_sessionStorage = $storage; + } + + /** + * Getter. + * + * @return CoreExt_Session_Storage_Interface + */ + public function getSessionStorage() + { + if (is_null($this->_sessionStorage)) { + require_once 'CoreExt/Session/Storage/Default.php'; + $this->setSessionStorage(new CoreExt_Session_Storage_Default([ + 'session_auto_start' => $this->getOption('session_auto_start') + ])); + } + + return $this->_sessionStorage; + } + + /** + * Getter. + * + * Retorna o array de dados gerenciados por CoreExt_Session_Storage_Interface, + * atualizando o atributo $_sessionData quando este diferir do valor retornado. + * + * @return array + * + * @see current() + */ + public function getSessionData() + { + if ($this->_sessionData != $this->getSessionStorage()->getSessionData()) { + $this->_sessionData = $this->getSessionStorage()->getSessionData(); + } + + return $this->_sessionData; + } + + /** + * @link http://br.php.net/manual/en/arrayaccess.offsetexists.php + */ + public function offsetExists($offset) + { + $value = $this->getSessionStorage()->read($offset); + + return isset($value); + } + + /** + * @link http://br.php.net/manual/en/arrayaccess.offsetget.php + */ + public function offsetGet($offset) + { + if ($this->offsetExists($offset)) { + return $this->getSessionStorage()->read($offset); + } + + return null; + } + + /** + * @link http://br.php.net/manual/en/arrayaccess.offsetset.php + */ + public function offsetSet($offset, $value) + { + $this->getSessionStorage()->write((string) $offset, $value); + } + + /** + * @link http://br.php.net/manual/en/arrayaccess.offsetunset.php + */ + public function offsetUnset($offset) + { + $this->getSessionStorage()->remove($offset); + } + + /** + * Implementa o método mágico __set(). + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string|int $key + * @param mixed $val + */ + public function __set($key, $value) + { + $this->offsetSet($key, $value); } - if (isset($options['sessionstorage'])) { - $this->setSessionStorage($options['sessionstorage']); + /** + * Implementa o método mágico __get(). + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string|int $key + * + * @return mixed + */ + public function __get($key) + { + return $this->offsetGet($key); } - $this->_options = array_merge($this->getOptions(), $options); - return $this; - } - - /** - * @see CoreExt_Configurable#getOptions() - */ - public function getOptions() - { - return $this->_options; - } - - /** - * Verifica se uma opção está setada. - * - * @param string $key - * @return bool - */ - protected function _hasOption($key) - { - return array_key_exists($key, $this->_options); - } - - /** - * Retorna um valor de opção de configuração ou NULL caso a opção não esteja - * setada. - * - * @param string $key - * @return mixed|NULL - */ - public function getOption($key) - { - return $this->_hasOption($key) ? $this->_options[$key] : NULL; - } - - /** - * Setter. - * @param CoreExt_Session_Storage_Interface $storage - */ - public function setSessionStorage(CoreExt_Session_Storage_Interface $storage) - { - $this->_sessionStorage = $storage; - } - - /** - * Getter. - * @return CoreExt_Session_Storage_Interface - */ - public function getSessionStorage() - { - if (is_null($this->_sessionStorage)) { - require_once 'CoreExt/Session/Storage/Default.php'; - $this->setSessionStorage(new CoreExt_Session_Storage_Default(array( - 'session_auto_start' => $this->getOption('session_auto_start') - ))); + /** + * Implementa o método mágico __isset(). + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string|int $key + * + * @return bool + */ + public function __isset($key) + { + return $this->offsetExists($key); } - return $this->_sessionStorage; - } - - /** - * Getter. - * - * Retorna o array de dados gerenciados por CoreExt_Session_Storage_Interface, - * atualizando o atributo $_sessionData quando este diferir do valor retornado. - * - * @return array - * @see current() - */ - public function getSessionData() - { - if ($this->_sessionData != $this->getSessionStorage()->getSessionData()) { - $this->_sessionData = $this->getSessionStorage()->getSessionData(); + + /** + * Implementa o método mágico __unset(). + * + * @link http://php.net/manual/en/language.oop5.overloading.php + * + * @param string|int $key + */ + public function __unset($key) + { + $this->offsetUnset($key); } - return $this->_sessionData; - } - - /** - * @link http://br.php.net/manual/en/arrayaccess.offsetexists.php - */ - public function offsetExists($offset) - { - $value = $this->getSessionStorage()->read($offset); - return isset($value); - } - - /** - * @link http://br.php.net/manual/en/arrayaccess.offsetget.php - */ - public function offsetGet($offset) - { - if ($this->offsetExists($offset)) { - return $this->getSessionStorage()->read($offset); + + /** + * @link http://br.php.net/manual/en/countable.count.php + * + * @return int + */ + public function count() + { + return $this->getSessionStorage()->count(); + } + + /** + * Implementa o método Iterator::current(). Chama método getSessionData() + * para atualizar o atributo $_sessionData, permitindo a ação da função + * {@link http://br.php.net/current current()}. + * + * @link http://br.php.net/manual/en/iterator.current.php + */ + public function current() + { + $this->getSessionData(); + + return current($this->_sessionData); + } + + /** + * @link http://br.php.net/manual/en/iterator.key.php + */ + public function key() + { + $data = $this->getSessionData(); + + return key($this->_sessionData); + } + + /** + * @link http://br.php.net/manual/en/iterator.next.php + */ + public function next() + { + $data = $this->getSessionData(); + + next($this->_sessionData); + } + + /** + * @link http://br.php.net/manual/en/iterator.rewind.php + */ + public function rewind() + { + $data = $this->getSessionData(); + + reset($this->_sessionData); + } + + /** + * @link http://br.php.net/manual/en/iterator.valid.php + */ + public function valid() + { + $key = key($this->_sessionData); + + return isset($key) ? true : false; } - return NULL; - } - - /** - * @link http://br.php.net/manual/en/arrayaccess.offsetset.php - */ - public function offsetSet($offset, $value) - { - $this->getSessionStorage()->write((string) $offset, $value); - } - - /** - * @link http://br.php.net/manual/en/arrayaccess.offsetunset.php - */ - public function offsetUnset($offset) - { - $this->getSessionStorage()->remove($offset); - } - - /** - * Implementa o método mágico __set(). - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string|int $key - * @param mixed $val - */ - public function __set($key, $value) - { - $this->offsetSet($key, $value); - } - - /** - * Implementa o método mágico __get(). - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string|int $key - * @return mixed - */ - public function __get($key) - { - return $this->offsetGet($key); - } - - /** - * Implementa o método mágico __isset(). - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string|int $key - * @return bool - */ - public function __isset($key) - { - return $this->offsetExists($key); - } - - /** - * Implementa o método mágico __unset(). - * @link http://php.net/manual/en/language.oop5.overloading.php - * @param string|int $key - */ - public function __unset($key) - { - $this->offsetUnset($key); - } - - /** - * @link http://br.php.net/manual/en/countable.count.php - * @return int - */ - public function count() - { - return $this->getSessionStorage()->count(); - } - - /** - * Implementa o método Iterator::current(). Chama método getSessionData() - * para atualizar o atributo $_sessionData, permitindo a ação da função - * {@link http://br.php.net/current current()}. - * - * @link http://br.php.net/manual/en/iterator.current.php - */ - public function current() - { - $this->getSessionData(); - return current($this->_sessionData); - } - - /** - * @link http://br.php.net/manual/en/iterator.key.php - */ - public function key() - { - $data = $this->getSessionData(); - return key($this->_sessionData); - } - - /** - * @link http://br.php.net/manual/en/iterator.next.php - */ - public function next() - { - $data = $this->getSessionData(); - next($this->_sessionData); - } - - /** - * @link http://br.php.net/manual/en/iterator.rewind.php - */ - public function rewind() - { - $data = $this->getSessionData(); - reset($this->_sessionData); - } - - /** - * @link http://br.php.net/manual/en/iterator.valid.php - */ - public function valid() - { - $key = key($this->_sessionData); - return isset($key) ? TRUE : FALSE; - } } diff --git a/ieducar/lib/CoreExt/Session/Storage/Abstract.php b/ieducar/lib/CoreExt/Session/Storage/Abstract.php index f9f1041b3a..10e42c2640 100644 --- a/ieducar/lib/CoreExt/Session/Storage/Abstract.php +++ b/ieducar/lib/CoreExt/Session/Storage/Abstract.php @@ -1,171 +1,133 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Session/Storage/Interface.php'; -/** - * CoreExt_Session_Storage_Abstract abstract class. - * - * Implementa operações básicas para facilitar a implementação de - * CoreExt_Session_Storage_Interface. - * - * Opções disponíveis: - * - session_name: o nome da session, o padrão é o valor definido no php.ini - * - session_auto_start: se a session deve ser iniciada na instanciação da - * classe. Padrão é TRUE - * - session_auto_shutdown: se um método de shutdown deve ser chamado no - * encerramento da execução do script PHP. Padrão é TRUE. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -abstract class CoreExt_Session_Storage_Abstract - implements CoreExt_Session_Storage_Interface, Countable +abstract class CoreExt_Session_Storage_Abstract implements CoreExt_Session_Storage_Interface, Countable { - /** - * Flag para definir se a session foi iniciada ou não, útil para impedir que - * funções que enviem headers sejam chamadas novamente (session_start, p.ex.) - * @var bool - */ - protected static $_sessionStarted = FALSE; + /** + * Flag para definir se a session foi iniciada ou não, útil para impedir que + * funções que enviem headers sejam chamadas novamente (session_start, p.ex.) + * + * @var bool + */ + protected static $_sessionStarted = false; - /** - * Id da session atual. - * @var string - */ - protected static $_sessionId = NULL; + /** + * Id da session atual. + * + * @var string + */ + protected static $_sessionId = null; - /** - * Opções de configuração geral da classe. - * @var array - */ - protected $_options = array( - 'session_name' => NULL, - 'session_auto_start' => TRUE, - 'session_auto_shutdown' => TRUE - ); + /** + * Opções de configuração geral da classe. + * + * @var array + */ + protected $_options = [ + 'session_name' => null, + 'session_auto_start' => true, + 'session_auto_shutdown' => true + ]; - /** - * Construtor. - * @param array $options Array de opções de configuração. - */ - public function __construct(array $options = array()) - { - $this->_init($options); + /** + * Construtor. + * + * @param array $options Array de opções de configuração. + */ + public function __construct(array $options = []) + { + $this->_init($options); - if (TRUE == $this->getOption('session_auto_shutdown')) { - register_shutdown_function(array($this, 'shutdown')); + if (true == $this->getOption('session_auto_shutdown')) { + register_shutdown_function([$this, 'shutdown']); + } } - } - /** - * Método de inicialização do storage. As subclasses devem sobrescrever - * este método para alterar o comportamento do mecanismo de session do PHP. - * - * @return CoreExt_Session_Storage_Abstract Provê interfae fluída - */ - protected function _init(array $options = array()) - { - $this->setOptions($options); - } + /** + * Método de inicialização do storage. As subclasses devem sobrescrever + * este método para alterar o comportamento do mecanismo de session do PHP. + * + * @param array $options + * + * @return void + */ + protected function _init(array $options = []) + { + $this->setOptions($options); + } - /** - * @see CoreExt_Configurable#setOptions($options) - */ - public function setOptions(array $options = array()) - { - $this->_options = array_merge($this->getOptions(), $options); - return $this; - } + /** + * @see CoreExt_Configurable#setOptions($options) + */ + public function setOptions(array $options = []) + { + $this->_options = array_merge($this->getOptions(), $options); - /** - * @see CoreExt_Configurable#getOptions() - */ - public function getOptions() - { - return $this->_options; - } + return $this; + } - /** - * Verifica se uma opção está setada. - * - * @param string $key - * @return bool - */ - protected function _hasOption($key) - { - return array_key_exists($key, $this->_options); - } + /** + * @see CoreExt_Configurable#getOptions() + */ + public function getOptions() + { + return $this->_options; + } - /** - * Retorna um valor de opção de configuração ou NULL caso a opção não esteja - * setada. - * - * @param string $key - * @return mixed|NULL - */ - public function getOption($key) - { - return $this->_hasOption($key) ? $this->_options[$key] : NULL; - } + /** + * Verifica se uma opção está setada. + * + * @param string $key + * + * @return bool + */ + protected function _hasOption($key) + { + return array_key_exists($key, $this->_options); + } - /** - * Getter. - * @return string - */ - public static function getSessionId() - { - return self::$_sessionId; - } + /** + * Retorna um valor de opção de configuração ou NULL caso a opção não esteja + * setada. + * + * @param string $key + * + * @return mixed|NULL + */ + public function getOption($key) + { + return $this->_hasOption($key) ? $this->_options[$key] : null; + } + + /** + * Getter. + * + * @return string + */ + public static function getSessionId() + { + return self::$_sessionId; + } - /** - * Getter. - * @return bool - */ - public static function isStarted() - { - return self::$_sessionStarted; - } + /** + * Getter. + * + * @return bool + */ + public static function isStarted() + { + return self::$_sessionStarted; + } - /** - * Getter. - * - * Deve ser implementado pelas subclasses para retornar o array de dados - * persistidos na session, permitindo que clientes iterem livremente pelos - * dados. - * - * @return array - */ - public abstract function getSessionData(); -} \ No newline at end of file + /** + * Getter. + * + * Deve ser implementado pelas subclasses para retornar o array de dados + * persistidos na session, permitindo que clientes iterem livremente pelos + * dados. + * + * @return array + */ + abstract public function getSessionData(); +} diff --git a/ieducar/lib/CoreExt/Session/Storage/Default.php b/ieducar/lib/CoreExt/Session/Storage/Default.php index ec1ba5a7ca..2acaa02904 100644 --- a/ieducar/lib/CoreExt/Session/Storage/Default.php +++ b/ieducar/lib/CoreExt/Session/Storage/Default.php @@ -1,164 +1,120 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Session/Storage/Abstract.php'; -/** - * CoreExt_Session_Storage_Default class. - * - * Storage de session padrão de CoreExt_Session, usa o mecanismo built-in do - * PHP. - * - * Opções disponíveis: - * - session_use_cookies: se é para setar um cookie de session no browser do - * usuário. Usa o valor configurado no php.ini caso não informado - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Session_Storage_Default extends CoreExt_Session_Storage_Abstract { - /** - * @see CoreExt_Session_Storage_Abstract#_init() - */ - protected function _init(array $options = array()) - { - $options = array_merge(array( - 'session_use_cookies' => ini_get('session.use_cookies') - ), $options); - - parent::_init($options); - - if (!is_null($this->getOption('session_name'))) { - session_name($this->getOption('session_name')); + /** + * @see CoreExt_Session_Storage_Abstract#_init() + */ + protected function _init(array $options = []) + { + $options = array_merge([ + 'session_use_cookies' => ini_get('session.use_cookies') + ], $options); + + parent::_init($options); + + if (!is_null($this->getOption('session_name'))) { + session_name($this->getOption('session_name')); + } + + if (!is_null(self::$_sessionId)) { + @session_id(self::$_sessionId); + } + + if (true == $this->getOption('session_auto_start')) { + $this->start(); + } } - if (!is_null(self::$_sessionId)) { - @session_id(self::$_sessionId); + /** + * @see CoreExt_Session_Storage_Interface#read($key) + */ + public function read($key) + { + $returnValue = null; + + if (isset($_SESSION[$key])) { + $returnValue = $_SESSION[$key]; + } + + return $returnValue; } - if (TRUE == $this->getOption('session_auto_start')) { - $this->start(); + /** + * @see CoreExt_Session_Storage_Interface#write($key, $value) + */ + public function write($key, $value) + { + $_SESSION[$key] = $value; } - } - /** - * @see CoreExt_Session_Storage_Interface#read($key) - */ - public function read($key) - { - $returnValue = NULL; + /** + * @see CoreExt_Session_Storage_Interface#remove($key) + */ + public function remove($key) + { + unset($_SESSION[$key]); + } - if (isset($_SESSION[$key])) { - $returnValue = $_SESSION[$key]; + /** + * @see CoreExt_Session_Storage_Interface#start() + */ + public function start() + { + if (!$this->isStarted() && @session_start()) { + self::$_sessionStarted = true; + self::$_sessionId = session_id(); + } } - return $returnValue; - } - - /** - * @see CoreExt_Session_Storage_Interface#write($key, $value) - */ - public function write($key, $value) - { - $_SESSION[$key] = $value; - } - - /** - * @see CoreExt_Session_Storage_Interface#remove($key) - */ - public function remove($key) - { - unset($_SESSION[$key]); - } - - /** - * @see CoreExt_Session_Storage_Interface#start() - */ - public function start() - { - if (!$this->isStarted() && @session_start()) { - self::$_sessionStarted = TRUE; - self::$_sessionId = session_id(); + /** + * @see CoreExt_Session_Storage_Interface#destroy() + */ + public function destroy() + { + if ($this->isStarted()) { + return session_destroy(); + } } - } - - /** - * @see CoreExt_Session_Storage_Interface#destroy() - */ - public function destroy() - { - if ($this->isStarted()) { - return session_destroy(); + + /** + * @see CoreExt_Session_Storage_Interface#regenerate() + */ + public function regenerate($destroy = false) + { + if ($this->isStarted()) { + session_regenerate_id($destroy); + self::$_sessionId = session_id(); + } } - } - - /** - * @see CoreExt_Session_Storage_Interface#regenerate() - */ - public function regenerate($destroy = FALSE) - { - if ($this->isStarted()) { - session_regenerate_id($destroy); - self::$_sessionId = session_id(); + + /** + * Persiste os dados da session no sistema de arquivos. + * + * @see CoreExt_Session_Storage_Interface#shutdown() + */ + public function shutdown() + { + if ($this->isStarted()) { + session_write_close(); + } + } + + /** + * @link http://br.php.net/manual/en/countable.count.php + */ + public function count() + { + return count($_SESSION); } - } - - /** - * Persiste os dados da session no sistema de arquivos. - * @see CoreExt_Session_Storage_Interface#shutdown() - */ - public function shutdown() - { - if ($this->isStarted()) { - session_write_close(); + + /** + * @see CoreExt_Session_Storage_Abstract#getSessionData() + */ + public function getSessionData() + { + return $_SESSION; } - } - - /** - * @link http://br.php.net/manual/en/countable.count.php - */ - public function count() - { - return count($_SESSION); - } - - /** - * @see CoreExt_Session_Storage_Abstract#getSessionData() - */ - public function getSessionData() - { - return $_SESSION; - } } diff --git a/ieducar/lib/CoreExt/Session/Storage/Interface.php b/ieducar/lib/CoreExt/Session/Storage/Interface.php index fb6f8f7d0d..d280612374 100644 --- a/ieducar/lib/CoreExt/Session/Storage/Interface.php +++ b/ieducar/lib/CoreExt/Session/Storage/Interface.php @@ -1,88 +1,50 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Configurable.php'; -/** - * CoreExt_Session_Storage_Interface interface. - * - * Interface mínima para que um storage de session possa ser criado. Define - * os métodos básicos de escrita e inicialização/destruição de uma session. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Session - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Session_Storage_Interface extends CoreExt_Configurable { - /** - * Inicializa a session. - */ - public function start(); - - /** - * - * @param string $key - * @return mixed - */ - public function read($key); - - /** - * Persiste um dado valor na session. - * @param string $key - * @param mixed $value - */ - public function write($key, $value); - - /** - * Remove/apaga um dado na session. - * @param string $key - */ - public function remove($key); - - /** - * Destrói os dados de uma session. - */ - public function destroy(); - - /** - * Gera um novo id para a session. - */ - public function regenerate($destroy = FALSE); - - /** - * Persiste os dados da session no storage definido ao final da execução - * do script PHP. - */ - public function shutdown(); -} \ No newline at end of file + /** + * Inicializa a session. + */ + public function start(); + + /** + * + * @param string $key + * + * @return mixed + */ + public function read($key); + + /** + * Persiste um dado valor na session. + * + * @param string $key + * @param mixed $value + */ + public function write($key, $value); + + /** + * Remove/apaga um dado na session. + * + * @param string $key + */ + public function remove($key); + + /** + * Destrói os dados de uma session. + */ + public function destroy(); + + /** + * Gera um novo id para a session. + */ + public function regenerate($destroy = false); + + /** + * Persiste os dados da session no storage definido ao final da execução + * do script PHP. + */ + public function shutdown(); +} diff --git a/ieducar/lib/CoreExt/Singleton.php b/ieducar/lib/CoreExt/Singleton.php index 9f6d03be49..16dc5a6b84 100644 --- a/ieducar/lib/CoreExt/Singleton.php +++ b/ieducar/lib/CoreExt/Singleton.php @@ -1,101 +1,61 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Singleton - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * CoreExt_Singleton abstract class. - * - * Funciona como uma interface de atalho para minimizar a duplicação de código - * para criar instâncias singleton. Internamente, entretanto, funciona como um - * {@link http://martinfowler.com/eaaCatalog/registry.html Registry} já que - * todas as suas subclasses estarão armazenadas em um array estático desta - * classe. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @link http://martinfowler.com/eaaCatalog/registry.html Registry pattern - * @package CoreExt_Singleton - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ abstract class CoreExt_Singleton { - /** - * A instância singleton de CoreExt_Singleton - * @var array - */ - private static $_instance = array(); + /** + * A instância singleton de CoreExt_Singleton + * + * @var array + */ + private static $_instance = []; + + /** + * Construtor. + */ + private function __construct() + { + } - /** - * Construtor. - */ - private function __construct() - { - } + /** + * Sobrescreva esse método para garantir que a subclasse possa criar um + * singleton. Esta deve fazer uma chamada ao método _getInstance, passando + * uma string que tenha como valor o nome da classe. Uma forma conveniente + * de fazer isso é chamando _getInstance passando como parâmetro a constante + * mágica __CLASS__. + * + * Exemplo: + * + * + * + * @return void + * + * @throws CoreExt_Exception + */ + public static function getInstance() + { + require_once 'CoreExt/Exception.php'; + throw new CoreExt_Exception('É necessário sobrescrever o método "getInstance()" de CoreExt_Singleton.'); + } - /** - * Sobrescreva esse método para garantir que a subclasse possa criar um - * singleton. Esta deve fazer uma chamada ao método _getInstance, passando - * uma string que tenha como valor o nome da classe. Uma forma conveniente - * de fazer isso é chamando _getInstance passando como parâmetro a constante - * mágica __CLASS__. - * - * Exemplo: - * - * - * - * @return CoreExt_Singleton - */ - public static function getInstance() - { - require_once 'CoreExt/Exception.php'; - throw new CoreExt_Exception('É necessário sobrescrever o método "getInstance()" de CoreExt_Singleton.'); - } + /** + * Retorna uma instância singleton, instanciando-a quando necessário. + * + * @param string $self Nome da subclasse de CoreExt_Singleton que será instanciada + * + * @return CoreExt_Singleton + */ + protected static function _getInstance($self) + { + if (!isset(self::$_instance[$self])) { + self::$_instance[$self] = new $self(); + } - /** - * Retorna uma instância singleton, instanciando-a quando necessário. - * - * @param string $self Nome da subclasse de CoreExt_Singleton que será instanciada - * @return CoreExt_Singleton - */ - protected static function _getInstance($self) - { - if (!isset(self::$_instance[$self])) { - self::$_instance[$self] = new $self(); + return self::$_instance[$self]; } - return self::$_instance[$self]; - } -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Validate/Abstract.php b/ieducar/lib/CoreExt/Validate/Abstract.php index f6f2989210..7e4da43eae 100644 --- a/ieducar/lib/CoreExt/Validate/Abstract.php +++ b/ieducar/lib/CoreExt/Validate/Abstract.php @@ -1,289 +1,265 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Interface.php'; -/** - * CoreExt_Validate_Abstract abstract class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ abstract class CoreExt_Validate_Abstract implements CoreExt_Validate_Interface { - /** - * Opções de configuração geral da classe. - * @var array - */ - protected $_options = array( - 'required' => TRUE, - 'trim' => TRUE, - ); + /** + * Opções de configuração geral da classe. + * + * @var array + */ + protected $_options = [ + 'required' => true, + 'trim' => true, + ]; + + /** + * Valor não sanitizado que foi informado ao validador. + * + * @var mixed + */ + protected $_value = null; - /** - * Valor não sanitizado que foi informado ao validador. - * @var mixed - */ - protected $_value = NULL; + /** + * Valor sanitizado. + * + * @var mixed + */ + protected $_sanitized = null; - /** - * Valor sanitizado. - * @var mixed - */ - protected $_sanitized = NULL; + /** + * Mensagem padrão para erros de valor obrigatório. + * + * @var string + */ + protected $_requiredMessage = 'Obrigatório.'; - /** - * Mensagem padrão para erros de valor obrigatório. - * @var string - */ - protected $_requiredMessage = 'Obrigatório.'; + /** + * Mensagem padrão para erros de invalidez. + * + * @var string + */ + protected $_invalidMessage = 'Inválido.'; - /** - * Mensagem padrão para erros de invalidez. - * @var string - */ - protected $_invalidMessage = 'Inválido.'; + /** + * Construtor. + * + * Pode receber array com opções de configuração da classe. + * + * @param array $options + */ + public function __construct(array $options = []) + { + $this->_options = array_merge($this->getOptions(), $this->_getDefaultOptions()); + + $this->setOptions($options); + } - /** - * Construtor. - * - * Pode receber array com opções de configuração da classe. - * - * @param array $options - */ - public function __construct(array $options = array()) - { - $this->_options = array_merge($this->getOptions(), $this->_getDefaultOptions()); - $this->setOptions($options); - } + /** + * Configura as opções do validador. + * + * Método de checagem de opções inspirado na técnica empregada no + * {@link http://www.symfony-project.org symfony framework}. + * + * @param array $options + * + * @throws InvalidArgumentException Lança exceção não verificada caso alguma + * opção passada ao método não exista na definição da classe + */ + public function setOptions(array $options = []) + { + $defaultOptions = array_keys($this->getOptions()); + $passedOptions = array_keys($options); - /** - * Configura as opções do validador. - * - * Método de checagem de opções inspirado na técnica empregada no - * {@link http://www.symfony-project.org symfony framework}. - * - * @param array $options - * @throws InvalidArgumentException Lança exceção não verificada caso alguma - * opção passada ao método não exista na definição da classe - */ - public function setOptions(array $options = array()) - { - $defaultOptions = array_keys($this->getOptions()); - $passedOptions = array_keys($options); + if (0 < count(array_diff($passedOptions, $defaultOptions))) { + throw new InvalidArgumentException( + sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) + ); + } - if (0 < count(array_diff($passedOptions, $defaultOptions))) { - throw new InvalidArgumentException( - sprintf('A classe %s não suporta as opções: %s.', get_class($this), implode(', ', $passedOptions)) - ); + $this->_options = array_merge($this->getOptions(), $options); } - $this->_options = array_merge($this->getOptions(), $options); - } + /** + * @see CoreExt_Validate_Interface#getOptions() + */ + public function getOptions() + { + return $this->_options; + } - /** - * @see CoreExt_Validate_Interface#getOptions() - */ - public function getOptions() - { - return $this->_options; - } + /** + * Verifica se uma opção está setada. + * + * @param string $key + * + * @return bool + */ + protected function _hasOption($key) + { + return + isset($this->_options[$key]) && + !$this->_isEmpty($this->_options[$key]); + } - /** - * Verifica se uma opção está setada. - * - * @param string $key - * @return bool - */ - protected function _hasOption($key) - { - return - isset($this->_options[$key]) && - !$this->_isEmpty($this->_options[$key]); - } + /** + * Retorna um valor de opção de configuração ou NULL caso a opção não esteja + * setada. + * + * @param string $key + * + * @return mixed|NULL + */ + public function getOption($key) + { + return $this->_hasOption($key) ? $this->_options[$key] : null; + } - /** - * Retorna um valor de opção de configuração ou NULL caso a opção não esteja - * setada. - * - * @param string $key - * @return mixed|NULL - */ - public function getOption($key) - { - return $this->_hasOption($key) ? $this->_options[$key] : NULL; - } + /** + * Permite que uma classe que estenda CoreExt_Validate_Abstract a definir + * valores de opções pré-definidos adequados ao caso específico. + * + * @return array + */ + abstract protected function _getDefaultOptions(); - /** - * Permite que uma classe que estenda CoreExt_Validate_Abstract a definir - * valores de opções pré-definidos adequados ao caso específico. - * - * @return array - */ - protected abstract function _getDefaultOptions(); + /** + * @see CoreExt_Validate_Interface#isValid($value) + */ + public function isValid($value) + { + $this->_value = $value; + $value = $this->_sanitize($value); - /** - * @see CoreExt_Validate_Interface#isValid($value) - */ - public function isValid($value) - { - $this->_value = $value; - $value = $this->_sanitize($value); + if (true == $this->getOption('trim') && is_string($value)) { + $value = trim($value); + } - if (TRUE == $this->getOption('trim') && is_string($value)) { - $value = trim($value); - } + $this->_sanitized = $value; - $this->_sanitized = $value; + if (true == $this->getOption('required') && $this->_isEmpty($value)) { + throw new Exception($this->_requiredMessage); + } - if (TRUE == $this->getOption('required') && $this->_isEmpty($value)) { - throw new Exception($this->_requiredMessage); + return $this->_validate($value); } - return $this->_validate($value); - } + /** + * Toda classe que estende CoreExt_Validate_Abstract deve implementar esse + * método com a lógica de validação adequada. + * + * @param string $value + * + * @return bool + */ + abstract protected function _validate($value); - /** - * Toda classe que estende CoreExt_Validate_Abstract deve implementar esse - * método com a lógica de validação adequada. - * - * @param string $value - * @return bool - */ - protected abstract function _validate($value); + /** + * Realiza uma sanitização + * + * @param mixed $value + * + * @return mixed + */ + protected function _sanitize($value) + { + return $value; + } - /** - * Realiza uma sanitização - * @param mixed $value - * @return mixed - */ - protected function _sanitize($value) - { - return $value; - } + /** + * Verifica se um dado valor está vazio. + * + * Como vazio, entende-se string vazia (''), array sem itens (array()), o + * valor NULL e zero (0) numérico. + * + * @param mixed $value + * + * @return bool + */ + protected function _isEmpty($value) + { + return in_array( + $value, + ['', [], null], + true + ); + } - /** - * Verifica se um dado valor está vazio. - * - * Como vazio, entende-se string vazia (''), array sem itens (array()), o - * valor NULL e zero (0) numérico. - * - * @param mixed $value - * @return bool - */ - protected function _isEmpty($value) - { - return in_array( - $value, array('', array(), NULL), TRUE - ); - } + /** + * Retorna uma mensagem de erro configurada em $_options. + * + * A mensagem de erro pode ser uma string ou um array. Se for uma string, + * ocorrerá a substituição dos placeholders. Se for um array, deverá ser + * especificado duas mensagens de erro, uma para a forma singular e outra + * para o plural. O placeholder @value será verificado para definir se a + * mensagem deve ser formatada no plural ou no singular. + * + * Exemplo de array de mensagem de erro que usa variante de número: + * + * + * '@value problema encontrado.' + * 'plural' => '@value problemas encontrados.' + * ) + * ); + * + * // Iria imprimir: + * // singular (@value = 1): 1 problema encontrado + * // plural (@value = 4): 4 problemas encontrados + * + * + * @param array|string $key O identificador da mensagem no array $_options + * @param array $options Array associativo para substituição de valores + * + * @return string + * + * @todo Implementar substituição com formatação padrão, semelhante ao + * a função Drupal {@link http://api.drupal.org/t t()}. + * @todo Implementar formatação singular/plural em uma classe diferente, + * como método público, permitindo realizar o teste. + */ + protected function _getErrorMessage($key, array $options = []) + { + $message = $this->getOption($key); - /** - * Retorna uma mensagem de erro configurada em $_options. - * - * A mensagem de erro pode ser uma string ou um array. Se for uma string, - * ocorrerá a substituição dos placeholders. Se for um array, deverá ser - * especificado duas mensagens de erro, uma para a forma singular e outra - * para o plural. O placeholder @value será verificado para definir se a - * mensagem deve ser formatada no plural ou no singular. - * - * Exemplo de array de mensagem de erro que usa variante de número: - * - * - * '@value problema encontrado.' - * 'plural' => '@value problemas encontrados.' - * ) - * ); - * - * // Iria imprimir: - * // singular (@value = 1): 1 problema encontrado - * // plural (@value = 4): 4 problemas encontrados - * - * - * @param array|string $key O identificador da mensagem no array $_options - * @param array $options Array associativo para substituição de valores - * @return string - * @todo Implementar substituição com formatação padrão, semelhante ao - * a função Drupal {@link http://api.drupal.org/t t()}. - * @todo Implementar formatação singular/plural em uma classe diferente, - * como método público, permitindo realizar o teste. - */ - protected function _getErrorMessage($key, array $options = array()) - { - $message = $this->getOption($key); + if (is_array($message)) { + // Verifica o tipo de @value para determinar a quantidade de $count + if (is_array($options['@value'])) { + $count = count($options['@value']); + } elseif (is_numeric($options['@value'])) { + $count = count($options['@value']); + } else { + $count = 1; + } - if (is_array($message)) { - // Verifica o tipo de @value para determinar a quantidade de $count - if (is_array($options['@value'])) { - $count = count($options['@value']); - } - elseif (is_numeric($options['@value'])) { - $count = count($options['@value']); - } - else { - $count = 1; - } + if (1 < $count) { + $message = $message['plural']; + $options['@value'] = implode(', ', $options['@value']); + } else { + $message = $message['singular']; + $options['@value'] = array_shift($options['@value']); + } + } - if (1 < $count) { - $message = $message['plural']; - $options['@value'] = implode(', ', $options['@value']); - } - else { - $message = $message['singular']; - $options['@value'] = array_shift($options['@value']); - } + return strtr($message, $options); } - return strtr($message, $options); - } - - /** - * @see CoreExt_Validate_Interface#getValue() - */ - public function getValue() - { - return $this->_value; - } + /** + * @see CoreExt_Validate_Interface#getValue() + */ + public function getValue() + { + return $this->_value; + } - /** - * @see CoreExt_Validate_Interface#getSanitizedValue() - */ - public function getSanitizedValue() - { - return $this->_sanitized; - } + /** + * @see CoreExt_Validate_Interface#getSanitizedValue() + */ + public function getSanitizedValue() + { + return $this->_sanitized; + } } diff --git a/ieducar/lib/CoreExt/Validate/Choice.php b/ieducar/lib/CoreExt/Validate/Choice.php index 87c6364be0..864236fff1 100644 --- a/ieducar/lib/CoreExt/Validate/Choice.php +++ b/ieducar/lib/CoreExt/Validate/Choice.php @@ -1,109 +1,78 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Abstract.php'; -/** - * CoreExt_Validate_Choice class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Validate_Choice extends CoreExt_Validate_Abstract { - /** - * @see CoreExt_Validate_Abstract#_getDefaultOptions() - */ - protected function _getDefaultOptions() - { - $options = array( - 'choices' => array(), - 'multiple' => FALSE, - 'trim' => FALSE, - 'choice_error' => 'A opção "@value" não existe.', - ); + /** + * @see CoreExt_Validate_Abstract#_getDefaultOptions() + */ + protected function _getDefaultOptions() + { + $options = [ + 'choices' => [], + 'multiple' => false, + 'trim' => false, + 'choice_error' => 'A opção "@value" não existe.', + ]; - $options['multiple_error'] = array( - 'singular' => $options['choice_error'], - 'plural' => 'As opções "@value" não existem.' - ); + $options['multiple_error'] = [ + 'singular' => $options['choice_error'], + 'plural' => 'As opções "@value" não existem.' + ]; - return $options; - } + return $options; + } - /** - * @see CoreExt_Validate_Abstract#_validate($value) - */ - protected function _validate($value) - { - if ($this->_hasOption('choices')) { - $value = $this->_getStringArray($value); - $choices = $this->_getStringArray($this->getOption('choices')); + /** + * @see CoreExt_Validate_Abstract#_validate($value) + */ + protected function _validate($value) + { + if ($this->_hasOption('choices')) { + $value = $this->_getStringArray($value); + $choices = $this->_getStringArray($this->getOption('choices')); - if ($this->_hasOption('multiple') && FALSE == $this->getOption('multiple')) { - if (in_array($value, $choices, TRUE)) { - return TRUE; + if ($this->_hasOption('multiple') && false == $this->getOption('multiple')) { + if (in_array($value, $choices, true)) { + return true; + } + throw new Exception($this->_getErrorMessage('choice_error', ['@value' => $this->getSanitizedValue()])); + } else { + if (in_array($value, [$choices], true)) { + return true; + } + throw new Exception( + $this->_getErrorMessage( + 'multiple_error', + ['@value' => array_diff($value, $this->getOption('choices'))] + ) + ); + } } - throw new Exception($this->_getErrorMessage('choice_error', array('@value' => $this->getSanitizedValue()))); - } - else { - if (in_array($value, array($choices), TRUE)) { - return TRUE; - } - throw new Exception($this->_getErrorMessage( - 'multiple_error', - array('@value' => array_diff($value, $this->getOption('choices')))) - ); - } + + return true; } - return TRUE; - } - /** - * Retorna um array de strings ou um valor numérico como string. - * @param array|numeric $value - * @return array|string - */ - protected function _getStringArray($value) - { - if (is_array($value)) { - $return = array(); - foreach ($value as $v) { - $return[] = (string) $v; - } - return $return; + /** + * Retorna um array de strings ou um valor numérico como string. + * + * @param array|int|float $value + * + * @return array|string + */ + protected function _getStringArray($value) + { + if (is_array($value)) { + $return = []; + + foreach ($value as $v) { + $return[] = (string) $v; + } + + return $return; + } + + return (string) $value; } - return (string) $value; - } -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Validate/ChoiceMultiple.php b/ieducar/lib/CoreExt/Validate/ChoiceMultiple.php index 3c6d507b35..5adbcfe5d1 100644 --- a/ieducar/lib/CoreExt/Validate/ChoiceMultiple.php +++ b/ieducar/lib/CoreExt/Validate/ChoiceMultiple.php @@ -1,54 +1,17 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Choice.php'; -/** - * CoreExt_Validate_ChoiceMultiple class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Validate_ChoiceMultiple extends CoreExt_Validate_Choice { - /** - * @see CoreExt_Validate_Choice#_getDefaultOptions() - */ - protected function _getDefaultOptions() - { - return array_merge( - parent::_getDefaultOptions(), array('multiple' => TRUE) - ); - } -} \ No newline at end of file + /** + * @see CoreExt_Validate_Choice::_getDefaultOptions() + */ + protected function _getDefaultOptions() + { + return array_merge( + parent::_getDefaultOptions(), + ['multiple' => true] + ); + } +} diff --git a/ieducar/lib/CoreExt/Validate/Email.php b/ieducar/lib/CoreExt/Validate/Email.php index e23e309a2b..72e2997288 100644 --- a/ieducar/lib/CoreExt/Validate/Email.php +++ b/ieducar/lib/CoreExt/Validate/Email.php @@ -1,73 +1,36 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Abstract.php'; -/** - * CoreExt_Validate_Numeric class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Validate_Email extends CoreExt_Validate_Abstract { - /** - * @see CoreExt_Validate_Abstract#_getDefaultOptions() - */ - protected function _getDefaultOptions() - { - return array( - 'invalid' => 'Email inválido.' - ); - } - - /** - * @see CoreExt_DataMapper#_getFindStatment($pkey) Sobre a conversão com floatval() - * @see CoreExt_Validate_Abstract#_validate($value) - */ - protected function _validate($value) - { - if (FALSE === filter_var($value, FILTER_VALIDATE_EMAIL)) { - throw new Exception($this->_getErrorMessage('invalid')); + /** + * @see CoreExt_Validate_Abstract#_getDefaultOptions() + */ + protected function _getDefaultOptions() + { + return [ + 'invalid' => 'Email inválido.' + ]; } - return TRUE; - } + /** + * @see CoreExt_DataMapper#_getFindStatment($pkey) Sobre a conversão com floatval() + * @see CoreExt_Validate_Abstract#_validate($value) + */ + protected function _validate($value) + { + if (false === filter_var($value, FILTER_VALIDATE_EMAIL)) { + throw new Exception($this->_getErrorMessage('invalid')); + } + + return true; + } - /** - * Mensagem padrão para erros de valor obrigatório. - * @var string - */ - protected $_requiredMessage = 'Informe um email válido.'; + /** + * Mensagem padrão para erros de valor obrigatório. + * + * @var string + */ + protected $_requiredMessage = 'Informe um email válido.'; } diff --git a/ieducar/lib/CoreExt/Validate/Interface.php b/ieducar/lib/CoreExt/Validate/Interface.php index 6d45e06eb9..5b85c517c6 100644 --- a/ieducar/lib/CoreExt/Validate/Interface.php +++ b/ieducar/lib/CoreExt/Validate/Interface.php @@ -1,65 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Configurable.php'; -/** - * CoreExt_Validate_Interface interface. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Validate_Interface extends CoreExt_Configurable { - /** - * Verifica se um dado valor é válido de acordo com a lógica implementada - * pela subclasse. - * - * @param $value - * @return bool - */ - public function isValid($value); + /** + * Verifica se um dado valor é válido de acordo com a lógica implementada + * pela subclasse. + * + * @param $value + * + * @return bool + */ + public function isValid($value); - /** - * Retorna o valor que foi para a validação. - * @return mixed - */ - public function getValue(); + /** + * Retorna o valor que foi para a validação. + * + * @return mixed + */ + public function getValue(); - /** - * Retorna o valor sanitizado após a validação. - * @return mixed - */ - public function getSanitizedValue(); -} \ No newline at end of file + /** + * Retorna o valor sanitizado após a validação. + * + * @return mixed + */ + public function getSanitizedValue(); +} diff --git a/ieducar/lib/CoreExt/Validate/Numeric.php b/ieducar/lib/CoreExt/Validate/Numeric.php index 24ebba487f..0d2a4f2a99 100644 --- a/ieducar/lib/CoreExt/Validate/Numeric.php +++ b/ieducar/lib/CoreExt/Validate/Numeric.php @@ -1,116 +1,77 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Abstract.php'; require_once 'CoreExt/Locale.php'; -/** - * CoreExt_Validate_Numeric class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Validate_Numeric extends CoreExt_Validate_Abstract { - /** - * @see CoreExt_Validate_Abstract#_getDefaultOptions() - */ - protected function _getDefaultOptions() - { - return array( - 'min' => NULL, - 'max' => NULL, - 'trim' => FALSE, - 'invalid' => 'O valor "@value" não é um tipo numérico', - 'min_error' => '"@value" é menor que o valor mínimo permitido (@min)', - 'max_error' => '"@value" é maior que o valor máximo permitido (@max)', - ); - } - - /** - * @see CoreExt_DataMapper#_getFindStatment($pkey) Sobre a conversão com floatval() - * @see CoreExt_Validate_Abstract#_validate($value) - */ - protected function _validate($value) - { - if (FALSE === $this->getOption('required') && is_null($value)) { - return TRUE; + /** + * @see CoreExt_Validate_Abstract::_getDefaultOptions() + */ + protected function _getDefaultOptions() + { + return [ + 'min' => null, + 'max' => null, + 'trim' => false, + 'invalid' => 'O valor "@value" não é um tipo numérico', + 'min_error' => '"@value" é menor que o valor mínimo permitido (@min)', + 'max_error' => '"@value" é maior que o valor máximo permitido (@max)', + ]; } - if (!is_numeric($value)) { - throw new Exception($this->_getErrorMessage('invalid', array('@value' => $value))); - } + /** + * @see CoreExt_DataMapper::_getFindStatment($pkey) Sobre a conversão com floatval() + * @see CoreExt_Validate_Abstract::_validate($value) + */ + protected function _validate($value) + { + if (false === $this->getOption('required') && is_null($value)) { + return true; + } - // Converte usando floatval para evitar problemas com range do tipo int. - $value = floatval($value); + if (!is_numeric($value)) { + throw new Exception($this->_getErrorMessage('invalid', ['@value' => $value])); + } - if ($this->_hasOption('min') && - $value < floatval($this->getOption('min'))) { - throw new Exception($this->_getErrorMessage('min_error', array( - '@value' => $value, '@min' => $this->getOption('min') - ))); - } + $value = floatval($value); - if ($this->_hasOption('max') && - $value > floatval($this->getOption('max'))) { - throw new Exception($this->_getErrorMessage('max_error', array( - '@value' => $value, '@max' => $this->getOption('max') - ))); + if ($this->_hasOption('min') && + $value < floatval($this->getOption('min'))) { + throw new Exception($this->_getErrorMessage('min_error', [ + '@value' => $value, '@min' => $this->getOption('min') + ])); + } + + if ($this->_hasOption('max') && + $value > floatval($this->getOption('max'))) { + throw new Exception($this->_getErrorMessage('max_error', [ + '@value' => $value, '@max' => $this->getOption('max') + ])); + } + + return true; } - return TRUE; - } + /** + * Realiza um sanitização de acordo com o locale, para permitir que valores + * flutuantes ou números de precisão arbitrária utilizem a pontuação sem + * localização. + * + * @see CoreExt_Validate_Abstract::_sanitize($value) + */ + protected function _sanitize($value) + { + $locale = CoreExt_Locale::getInstance(); + $decimalPoint = $locale->getCultureInfo('decimal_point'); - /** - * Realiza um sanitização de acordo com o locale, para permitir que valores - * flutuantes ou números de precisão arbitrária utilizem a pontuação sem - * localização. - * - * @see CoreExt_Validate_Abstract#_sanitize($value) - */ - protected function _sanitize($value) - { - $locale = CoreExt_Locale::getInstance(); - $decimalPoint = $locale->getCultureInfo('decimal_point'); + // Verifica se possui o ponto decimal do locale e substitui para o + // padrão do locale en_US (ponto ".") + if (false !== strstr($value, $decimalPoint)) { + $value = strtr($value, $decimalPoint, '.'); + $value = floatval($value); + } - // Verifica se possui o ponto decimal do locale e substitui para o - // padrão do locale en_US (ponto ".") - if (FALSE !== strstr($value, $decimalPoint)) { - $value = strtr($value, $decimalPoint, '.'); - $value = floatval($value); + return parent::_sanitize($value); } - - return parent::_sanitize($value); - } -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/Validate/String.php b/ieducar/lib/CoreExt/Validate/String.php index cc102f03a9..edf2156561 100644 --- a/ieducar/lib/CoreExt/Validate/String.php +++ b/ieducar/lib/CoreExt/Validate/String.php @@ -1,87 +1,55 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Abstract.php'; -/** - * CoreExt_Validate_String class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_Validate_String extends CoreExt_Validate_Abstract { - /** - * @see CoreExt_Validate_Abstract#_getDefaultOptions() - */ - protected function _getDefaultOptions() - { - return array( - 'min' => NULL, - 'max' => NULL, - 'min_error' => '"@value" é muito curto (@min caracteres no mínimo)', - 'max_error' => '"@value" é muito longo (@max caracteres no máximo)', - ); - } - - /** - * @see CoreExt_Validate_Abstract#_validate($value) - */ - protected function _validate($value) - { - $length = strlen($value); - - if ($this->_hasOption('min') && $length < $this->getOption('min')) { - throw new Exception($this->_getErrorMessage('min_error', - array('@value' => $this->getSanitizedValue(), '@min' => $this->getOption('min'))) - ); + /** + * @see CoreExt_Validate_Abstract#_getDefaultOptions() + */ + protected function _getDefaultOptions() + { + return [ + 'min' => null, + 'max' => null, + 'min_error' => '"@value" é muito curto (@min caracteres no mínimo)', + 'max_error' => '"@value" é muito longo (@max caracteres no máximo)', + ]; } - if ($this->_hasOption('max') && $length > $this->getOption('max')) { - throw new Exception($this->_getErrorMessage('max_error', - array('@value' => $this->getSanitizedValue(), '@max' => $this->getOption('max'))) - ); + /** + * @see CoreExt_Validate_Abstract#_validate($value) + */ + protected function _validate($value) + { + $length = strlen($value); + + if ($this->_hasOption('min') && $length < $this->getOption('min')) { + throw new Exception( + $this->_getErrorMessage( + 'min_error', + ['@value' => $this->getSanitizedValue(), '@min' => $this->getOption('min')] + ) + ); + } + + if ($this->_hasOption('max') && $length > $this->getOption('max')) { + throw new Exception( + $this->_getErrorMessage( + 'max_error', + ['@value' => $this->getSanitizedValue(), '@max' => $this->getOption('max')] + ) + ); + } + + return true; } - return TRUE; - } - - /** - * @see CoreExt_Validate_Abstract#_sanitize($value) - */ - protected function _sanitize($value) - { - return (string) parent::_sanitize($value); - } -} \ No newline at end of file + /** + * @see CoreExt_Validate_Abstract#_sanitize($value) + */ + protected function _sanitize($value) + { + return (string) parent::_sanitize($value); + } +} diff --git a/ieducar/lib/CoreExt/Validate/Validatable.php b/ieducar/lib/CoreExt/Validate/Validatable.php index c058e5f243..d793a3983a 100644 --- a/ieducar/lib/CoreExt/Validate/Validatable.php +++ b/ieducar/lib/CoreExt/Validate/Validatable.php @@ -1,77 +1,38 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Validate/Choice.php'; require_once 'CoreExt/Validate/ChoiceMultiple.php'; require_once 'CoreExt/Validate/String.php'; require_once 'CoreExt/Validate/Numeric.php'; -/** - * CoreExt_Validatable interface. - * - * A classe que implementar essa interface terá definir métodos que permitam - * relacionar uma propriedade a um CoreExt_Validate_Interface, criando um - * mecanismo simples e efetivo de validação. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_Validate - * @since Interface disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ interface CoreExt_Validate_Validatable { - /** - * Retorna TRUE caso a propriedade seja válida. - * - * @param string $key - * @return bool - */ - public function isValid($key = ''); + /** + * Retorna TRUE caso a propriedade seja válida. + * + * @param string $key + * + * @return bool + */ + public function isValid($key = ''); - /** - * Configura um CoreExt_Validate_Interface para uma propriedade da classe. - * - * @param string $key - * @param CoreExt_Validate_Interface $validator - * @return CoreExt_Validate_Validatable Provê interface fluída - */ - public function setValidator($key, CoreExt_Validate_Interface $validator); + /** + * Configura um CoreExt_Validate_Interface para uma propriedade da classe. + * + * @param string $key + * @param CoreExt_Validate_Interface $validator + * + * @return CoreExt_Validate_Validatable Provê interface fluída + */ + public function setValidator($key, CoreExt_Validate_Interface $validator); - /** - * Retorna a instância CoreExt_Validate_Interface para uma propriedade da - * classe ou NULL caso nenhum validador esteja atribuído. - * - * @param string $key - * @return CoreExt_Validate_Interface|NULL - */ - public function getValidator($key); -} \ No newline at end of file + /** + * Retorna a instância CoreExt_Validate_Interface para uma propriedade da + * classe ou NULL caso nenhum validador esteja atribuído. + * + * @param string $key + * + * @return CoreExt_Validate_Interface|NULL + */ + public function getValidator($key); +} diff --git a/ieducar/lib/CoreExt/View.php b/ieducar/lib/CoreExt/View.php index cb8770aa9d..c1b5153fd2 100644 --- a/ieducar/lib/CoreExt/View.php +++ b/ieducar/lib/CoreExt/View.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/View/Abstract.php'; -/** - * CoreExt_View class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_View extends CoreExt_View_Abstract { -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/View/Abstract.php b/ieducar/lib/CoreExt/View/Abstract.php index 01f796489a..257b2ef5f0 100644 --- a/ieducar/lib/CoreExt/View/Abstract.php +++ b/ieducar/lib/CoreExt/View/Abstract.php @@ -1,79 +1,47 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * CoreExt_View_Abstract abstract class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ abstract class CoreExt_View_Abstract { - /** - * Conteúdo gerado pela execução de um controller. - * @var string - */ - protected $_contents = NULL; + /** + * Conteúdo gerado pela execução de um controller. + * + * @var string + */ + protected $_contents = null; + + /** + * Setter. + * + * @param string $contents + * + * @return CoreExt_View_Abstract Provê interface fluída. + */ + public function setContents($contents) + { + $this->_contents = $contents; - /** - * Setter. - * - * @param string $contents - * @return CoreExt_View_Abstract Provê interface fluída. - */ - public function setContents($contents) - { - $this->_contents = $contents; - return $this; - } + return $this; + } - /** - * Getter. - * @return string - */ - public function getContents() - { - return $this->_contents; - } + /** + * Getter. + * + * @return string + */ + public function getContents() + { + return $this->_contents; + } - /** - * Implementação do método mágico __toString(). Retorna o valor de $contents. - * @link http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring - * @return string - */ - public function __toString() - { - return $this->getContents(); - } -} \ No newline at end of file + /** + * Implementação do método mágico __toString(). Retorna o valor de $contents. + * + * @link http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring + * + * @return string + */ + public function __toString() + { + return $this->getContents(); + } +} diff --git a/ieducar/lib/CoreExt/View/Helper/Abstract.php b/ieducar/lib/CoreExt/View/Helper/Abstract.php index 1e1810b43e..a8f4f35076 100644 --- a/ieducar/lib/CoreExt/View/Helper/Abstract.php +++ b/ieducar/lib/CoreExt/View/Helper/Abstract.php @@ -1,45 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/Singleton.php'; -/** - * CoreExt_View_Helper_Abstract abstract class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ abstract class CoreExt_View_Helper_Abstract extends CoreExt_Singleton { -} \ No newline at end of file +} diff --git a/ieducar/lib/CoreExt/View/Helper/TableHelper.php b/ieducar/lib/CoreExt/View/Helper/TableHelper.php index d87de9df91..c7f704c1bf 100644 --- a/ieducar/lib/CoreExt/View/Helper/TableHelper.php +++ b/ieducar/lib/CoreExt/View/Helper/TableHelper.php @@ -1,280 +1,278 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/View/Helper/Abstract.php'; -/** - * CoreExt_View_Helper_TableHelper class. - * - * Helper para a criação de tabelas HTML através de arrays associativos. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_View_Helper_TableHelper extends CoreExt_View_Helper_Abstract { - protected $_header = array(); - protected $_body = array(); - protected $_footer = array(); - - /** - * Construtor singleton. - */ - protected function __construct() - { - } - - /** - * Retorna uma instância singleton. - * @return CoreExt_View_Helper_Abstract - */ - public static function getInstance() - { - $instance = self::_getInstance(__CLASS__); - $instance->resetTable(); - return $instance; - } - - /** - * Reseta os dados da tabela. - * @return CoreExt_View_Helper_TableHelper Provê interface fluída - */ - public function resetTable() - { - $this->_header = array(); - $this->_body = array(); - $this->_footer = array(); - return $this; - } - - /** - * Adiciona um array para um row de tabela para a tag cabeçalho (thead). Cada - * valor do array precisa ser um array associativo, podendo conter os - * seguintes atributos: - * - * - data: o valor que será impresso na célula (td) da tabela - * - colspan: valor inteiro para colspan {@link } - * - attributes: array associativo onde o nome do atributo é o índice - * - * - * $table = CoreExt_View_Helper_TableHelper::getInstance(); - * - * $data = array( - * array('data' => 'Example 1', 'colspan' => 1), - * array('data' => 'Example 2', 'attributes' => array( - * 'class' => 'tdd1', 'style' => 'border: 1px dashed green' - * )) - * ); - * - * $table->addHeaderRow($data); - * print $table; - * - * // - * // - * // - * // - * // - * // - * // - * - * - * @param array $cols - * @return CoreExt_View_Helper_TableHelper Provê interface fluída - */ - public function addHeaderRow(array $cols, array $rowAttributes = array()) - { - $this->_header[] = array('row' => $cols, 'attributes' => $rowAttributes); - return $this; - } - - /** - * Adiciona um array para um row de tabela para a tag corpo (tbody). - * - * @param $cols - * @return CoreExt_View_Helper_TableHelper Provê interface fluída - * @see CoreExt_View_Helper_TableHelper::addHeaderRow(array $cols) - */ - public function addBodyRow(array $cols, array $rowAttributes = array()) - { - $this->_body[] = array('row' => $cols, 'attributes' => $rowAttributes); - return $this; - } - - /** - * Adiciona um array para um row de tabela para a tag rodapé (tfooter). - * - * @param $cols - * @return CoreExt_View_Helper_TableHelper Provê interface fluída - * @see CoreExt_View_Helper_TableHelper::addHeaderRow(array $cols) - */ - public function addFooterRow(array $cols, array $rowAttributes = array()) - { - $this->_footer[] = array('row' => $cols, 'attributes' => $rowAttributes); - return $this; - } - - /** - * Cria uma tabela HTML usando os valores passados para os métodos add*(). - * - * @param array $tableAttributes - * @return string - */ - public function createTable(array $tableAttributes = array()) - { - return sprintf( - '%s%s%s%s%s
Example 1Example 2
', - $this->_attributes($tableAttributes), - PHP_EOL, - $this->createHeader(TRUE), - $this->createBody(TRUE), - $this->createFooter(TRUE), - PHP_EOL - ); - } - - /** - * Cria a seção thead de uma tabela. - * @param bool $indent - * @return string - */ - public function createHeader($indent = FALSE) - { - return $this->_createHtml($this->_getTag('thead', $indent), $this->_header, $indent); - } - - /** - * Cria a seção tbody de uma tabela. - * @param bool $indent - * @return string - */ - public function createBody($indent = FALSE) - { - return $this->_createHtml($this->_getTag('tbody', $indent), $this->_body, $indent); - } - - /** - * Cria a seção tfooter de uma tabela. - * @param bool $indent - * @return string - */ - public function createFooter($indent = FALSE) - { - return $this->_createHtml($this->_getTag('tfooter', $indent), $this->_footer, $indent); - } - - /** - * Formata uma string para o uso de _createHtml(). - * - * @param string $name - * @param bool $indent - * @return string - */ - protected function _getTag($name, $indent = TRUE) - { - $indent = $indent ? ' ' : ''; - return sprintf('%s<%s>%s%s%s', $indent, $name, '%s', '%s', $indent, $name); - } - - /** - * Cria código Html de um row de tabela. - * - * @param string $closure - * @param array $rows - * @param bool $indent - * @return string - */ - protected function _createHtml($closure, $rows = array(), $indent = FALSE) - { - $html = ''; - $indent = $indent ? ' ' : ''; - - foreach ($rows as $cols) { - $row = ''; - - $cells = $cols['row']; - $rowAttributes = $cols['attributes']; - - foreach ($cells as $cell) { - $attributes = isset($cell['attributes']) ? $cell['attributes'] : array(); - $data = isset($cell['data']) ? $cell['data'] : ' '; - - if (isset($cell['colspan'])) { - $attributes['colspan'] = $cell['colspan']; - } + protected $_header = []; + protected $_body = []; + protected $_footer = []; + + /** + * Construtor singleton. + */ + protected function __construct() + { + } + + /** + * Retorna uma instância singleton. + * + * @return CoreExt_View_Helper_Abstract + */ + public static function getInstance() + { + $instance = self::_getInstance(__CLASS__); + $instance->resetTable(); + + return $instance; + } + + /** + * Reseta os dados da tabela. + * + * @return CoreExt_View_Helper_TableHelper Provê interface fluída + */ + public function resetTable() + { + $this->_header = []; + $this->_body = []; + $this->_footer = []; + + return $this; + } + + /** + * Adiciona um array para um row de tabela para a tag cabeçalho (thead). Cada + * valor do array precisa ser um array associativo, podendo conter os + * seguintes atributos: + * + * - data: o valor que será impresso na célula (td) da tabela + * - colspan: valor inteiro para colspan {@link } + * - attributes: array associativo onde o nome do atributo é o índice + * + * + * $table = CoreExt_View_Helper_TableHelper::getInstance(); + * + * $data = array( + * array('data' => 'Example 1', 'colspan' => 1), + * array('data' => 'Example 2', 'attributes' => array( + * 'class' => 'tdd1', 'style' => 'border: 1px dashed green' + * )) + * ); + * + * $table->addHeaderRow($data); + * print $table; + * + * // + * // + * // + * // + * // + * // + * // + * + * + * @param array $cols + * + * @return CoreExt_View_Helper_TableHelper Provê interface fluída + */ + public function addHeaderRow(array $cols, array $rowAttributes = []) + { + $this->_header[] = ['row' => $cols, 'attributes' => $rowAttributes]; + + return $this; + } + + /** + * Adiciona um array para um row de tabela para a tag corpo (tbody). + * + * @param $cols + * + * @return CoreExt_View_Helper_TableHelper Provê interface fluída + * + * @see CoreExt_View_Helper_TableHelper::addHeaderRow(array $cols) + */ + public function addBodyRow(array $cols, array $rowAttributes = []) + { + $this->_body[] = ['row' => $cols, 'attributes' => $rowAttributes]; + + return $this; + } + + /** + * Adiciona um array para um row de tabela para a tag rodapé (tfooter). + * + * @param $cols + * + * @return CoreExt_View_Helper_TableHelper Provê interface fluída + * + * @see CoreExt_View_Helper_TableHelper::addHeaderRow(array $cols) + */ + public function addFooterRow(array $cols, array $rowAttributes = []) + { + $this->_footer[] = ['row' => $cols, 'attributes' => $rowAttributes]; + + return $this; + } + + /** + * Cria uma tabela HTML usando os valores passados para os métodos add*(). + * + * @param array $tableAttributes + * + * @return string + */ + public function createTable(array $tableAttributes = []) + { + return sprintf( + '%s%s%s%s%s
Example 1Example 2
', + $this->_attributes($tableAttributes), + PHP_EOL, + $this->createHeader(true), + $this->createBody(true), + $this->createFooter(true), + PHP_EOL + ); + } - $row .= sprintf('%s %s%s', PHP_EOL, $indent, - $this->_attributes($attributes), $data); - } + /** + * Cria a seção thead de uma tabela. + * + * @param bool $indent + * + * @return string + */ + public function createHeader($indent = false) + { + return $this->_createHtml($this->_getTag('thead', $indent), $this->_header, $indent); + } - $html .= sprintf(' %s%s%s%s %s', $indent, - $this->_attributes($rowAttributes), $row, PHP_EOL, $indent, PHP_EOL); + /** + * Cria a seção tbody de uma tabela. + * + * @param bool $indent + * + * @return string + */ + public function createBody($indent = false) + { + return $this->_createHtml($this->_getTag('tbody', $indent), $this->_body, $indent); } - if (0 == strlen(trim($html))) { - return ''; + /** + * Cria a seção tfooter de uma tabela. + * + * @param bool $indent + * + * @return string + */ + public function createFooter($indent = false) + { + return $this->_createHtml($this->_getTag('tfooter', $indent), $this->_footer, $indent); } - return sprintf($closure, PHP_EOL, $html); - } - - /** - * Cria uma string de atributos HTML. - * - * @param array $attributes - * @return string - */ - protected function _attributes(array $attributes = array()) - { - if (0 == count($attributes)) { - return ''; + /** + * Formata uma string para o uso de _createHtml(). + * + * @param string $name + * @param bool $indent + * + * @return string + */ + protected function _getTag($name, $indent = true) + { + $indent = $indent ? ' ' : ''; + + return sprintf('%s<%s>%s%s%s', $indent, $name, '%s', '%s', $indent, $name); } - $html = array(); - ksort($attributes); - foreach ($attributes as $key => $value) { - $html[] = sprintf('%s="%s"', $key, $value); + /** + * Cria código Html de um row de tabela. + * + * @param string $closure + * @param array $rows + * @param bool $indent + * + * @return string + */ + protected function _createHtml($closure, $rows = [], $indent = false) + { + $html = ''; + $indent = $indent ? ' ' : ''; + + foreach ($rows as $cols) { + $row = ''; + + $cells = $cols['row']; + $rowAttributes = $cols['attributes']; + + foreach ($cells as $cell) { + $attributes = isset($cell['attributes']) ? $cell['attributes'] : []; + $data = isset($cell['data']) ? $cell['data'] : ' '; + + if (isset($cell['colspan'])) { + $attributes['colspan'] = $cell['colspan']; + } + + $row .= sprintf( + '%s %s%s', + PHP_EOL, + $indent, + $this->_attributes($attributes), + $data + ); + } + + $html .= sprintf( + ' %s%s%s%s %s', + $indent, + $this->_attributes($rowAttributes), + $row, + PHP_EOL, + $indent, + PHP_EOL + ); + } + + if (0 == strlen(trim($html))) { + return ''; + } + + return sprintf($closure, PHP_EOL, $html); + } + + /** + * Cria uma string de atributos HTML. + * + * @param array $attributes + * + * @return string + */ + protected function _attributes(array $attributes = []) + { + if (0 == count($attributes)) { + return ''; + } + + $html = []; + + ksort($attributes); + + foreach ($attributes as $key => $value) { + $html[] = sprintf('%s="%s"', $key, $value); + } + + return ' ' . implode(' ', $html); } - return ' ' . implode(' ', $html); - } - - /** - * Implementa método mágico __toString(). - * @link - */ - public function __toString() - { - return $this->createTable(); - } -} \ No newline at end of file + /** + * Implementa método mágico __toString(). + * + * @link + */ + public function __toString() + { + return $this->createTable(); + } +} diff --git a/ieducar/lib/CoreExt/View/Helper/UrlHelper.php b/ieducar/lib/CoreExt/View/Helper/UrlHelper.php index 15253c7b91..13b9543826 100644 --- a/ieducar/lib/CoreExt/View/Helper/UrlHelper.php +++ b/ieducar/lib/CoreExt/View/Helper/UrlHelper.php @@ -1,235 +1,207 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/View/Helper/Abstract.php'; -/** - * CoreExt_View_Helper_UrlHelper class. - * - * @author Eriksen Costa Paixão - * @category i-Educar - * @license @@license@@ - * @package CoreExt_View - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ class CoreExt_View_Helper_UrlHelper extends CoreExt_View_Helper_Abstract { - /** - * Constantes para definir que parte da URL deve ser gerada no método - * url(). - */ - const URL_SCHEME = 1; - const URL_HOST = 4; - const URL_PORT = 16; - const URL_USER = 32; - const URL_PASS = 64; - const URL_PATH = 128; - const URL_QUERY = 128; - const URL_FRAGMENT = 256; - - /** - * @var array - */ - private $_components = array( - 'scheme' => self::URL_SCHEME, - 'host' => self::URL_HOST, - 'port' => self::URL_PORT, - 'user' => self::URL_USER, - 'pass' => self::URL_PASS, - 'path' => self::URL_PATH, - 'query' => self::URL_QUERY, - 'fragment' => self::URL_FRAGMENT - ); - - /** - * URL base para a geração de url absoluta. - * @var string - */ - protected $_baseUrl = ''; - - /** - * Schema padrão para a geração de url absoluta. - * @var string - */ - protected $_schemeUrl = 'http://'; - - /** - * Construtor singleton. - */ - protected function __construct() - { - } - - /** - * Retorna uma instância singleton. - * @return CoreExt_View_Helper_Abstract - */ - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } - - /** - * Setter para $_baseUrl. - * @param string $baseUrl - */ - public static function setBaseUrl($baseUrl) - { - $instance = self::getInstance(); - $instance->_baseUrl = $baseUrl; - } - - /** - * Retorna uma URL formatada. Interface externa. - * - * A geração da URL é bastante dinâmica e simples, já que aceita tanto - * caminhos absolutos ou relativos. - * - * As opções para o array $options são: - * - absolute: gera uma URL absoluta - * - query: array associativo para criar uma query string (ver ex.) - * - fragment: adiciona um fragmento ao final da URL - * - components: um valor numérico que define até que componente deverá ser - * retornado na URL parseada. Uma valor de URL_HOST, por exemplo, retornaria - * os componentes URL_FRAGMENT e URL_HOST. Veja valores das constantes URL_* - * para saber qual o nível de detalhe desejado - * - * Exemplo: - * - * TRUE, - * 'query' => array('param1' => 'value1', 'param2' => 'value2'), - * 'fragment' => 'Fragment', - * 'components' => CoreExt_View_Helper_UrlHelper::URL_HOST - * ); - * // http://example.com/index?param1=value1¶m2=value2#Fragment - * - * $options = array( - * 'absolute' => TRUE, - * 'query' => array('param1' => 'value1', 'param2' => 'value2'), - * 'fragment' => 'Fragment', - * 'components' => CoreExt_View_Helper_UrlHelper::URL_HOST - * ); - * print CoreExt_View_Helper_UrlHelper::url('example.com/index', $options); - * // http://example.com - * - * - * @param string $path O caminho relativo ou absoluto da URL - * @param array $options Opções para geração da URL - * @return string - */ - public static function url($path, array $options = array()) - { - $instance = self::getInstance(); - return $instance->_url($path, $options); - } - - /** - * Retorna uma URL formatada. Veja a documentação de url(). - * - * @param string $path - * @param array $options - * @return string - */ - protected function _url($path, array $options = array()) - { - $url = array( - 'scheme' => '', - 'host' => '', - 'user' => '', - 'pass' => '', - 'path' => '', - 'query' => '', - 'fragment' => '' - ); - - $parsedUrl = parse_url($path); - $url = array_merge($url, $parsedUrl); - - // Adiciona "://" caso o scheme seja parseado (caso das URLs absolutas implícitas) - if ('' != $url['scheme']) { - $url['scheme'] = $url['scheme'] . '://'; + /** + * Constantes para definir que parte da URL deve ser gerada no método + * url(). + */ + const URL_SCHEME = 1; + const URL_HOST = 4; + const URL_PORT = 16; + const URL_USER = 32; + const URL_PASS = 64; + const URL_PATH = 128; + const URL_QUERY = 128; + const URL_FRAGMENT = 256; + + /** + * @var array + */ + private $_components = [ + 'scheme' => self::URL_SCHEME, + 'host' => self::URL_HOST, + 'port' => self::URL_PORT, + 'user' => self::URL_USER, + 'pass' => self::URL_PASS, + 'path' => self::URL_PATH, + 'query' => self::URL_QUERY, + 'fragment' => self::URL_FRAGMENT + ]; + + /** + * URL base para a geração de url absoluta. + * + * @var string + */ + protected $_baseUrl = ''; + + /** + * Schema padrão para a geração de url absoluta. + * + * @var string + */ + protected $_schemeUrl = 'http://'; + + /** + * Construtor singleton. + */ + protected function __construct() + { } - // Opções do método - if (isset($options['absolute'])) { - $url['scheme'] = $url['scheme'] != '' ? $url['scheme'] : $this->_schemeUrl; - $url['host'] = $url['host'] != '' ? $url['host'] : $this->_baseUrl . '/'; + /** + * Retorna uma instância singleton. + * + * @return CoreExt_View_Helper_Abstract + */ + public static function getInstance() + { + return self::_getInstance(__CLASS__); } - if (isset($options['query'])) { - $url['query'] = '?' . http_build_query($options['query']); + /** + * Setter para $_baseUrl. + * + * @param string $baseUrl + */ + public static function setBaseUrl($baseUrl) + { + $instance = self::getInstance(); + $instance->_baseUrl = $baseUrl; } - if (isset($options['fragment'])) { - $url['fragment'] = '#' . (string)$options['fragment']; + + /** + * Retorna uma URL formatada. Interface externa. + * + * A geração da URL é bastante dinâmica e simples, já que aceita tanto + * caminhos absolutos ou relativos. + * + * As opções para o array $options são: + * - absolute: gera uma URL absoluta + * - query: array associativo para criar uma query string (ver ex.) + * - fragment: adiciona um fragmento ao final da URL + * - components: um valor numérico que define até que componente deverá ser + * retornado na URL parseada. Uma valor de URL_HOST, por exemplo, retornaria + * os componentes URL_FRAGMENT e URL_HOST. Veja valores das constantes URL_* + * para saber qual o nível de detalhe desejado + * + * Exemplo: + * + * TRUE, + * 'query' => array('param1' => 'value1', 'param2' => 'value2'), + * 'fragment' => 'Fragment', + * 'components' => CoreExt_View_Helper_UrlHelper::URL_HOST + * ); + * // http://example.com/index?param1=value1¶m2=value2#Fragment + * + * $options = array( + * 'absolute' => TRUE, + * 'query' => array('param1' => 'value1', 'param2' => 'value2'), + * 'fragment' => 'Fragment', + * 'components' => CoreExt_View_Helper_UrlHelper::URL_HOST + * ); + * print CoreExt_View_Helper_UrlHelper::url('example.com/index', $options); + * // http://example.com + * + * + * @param string $path O caminho relativo ou absoluto da URL + * @param array $options Opções para geração da URL + * + * @return string + */ + public static function url($path, array $options = []) + { + $instance = self::getInstance(); + + return $instance->_url($path, $options); } - // Remove da URL final os componentes que tem valor maior que o especificado - // por 'components'. - if (isset($options['components'])) { - foreach ($this->_components as $key => $value) { - if ($value > $options['components']) { - unset($url[$key]); + /** + * Retorna uma URL formatada. Veja a documentação de url(). + * + * @param string $path + * @param array $options + * + * @return string + */ + protected function _url($path, array $options = []) + { + $url = [ + 'scheme' => '', + 'host' => '', + 'user' => '', + 'pass' => '', + 'path' => '', + 'query' => '', + 'fragment' => '' + ]; + + $parsedUrl = parse_url($path); + $url = array_merge($url, $parsedUrl); + + // Adiciona "://" caso o scheme seja parseado (caso das URLs absolutas implícitas) + if ('' != $url['scheme']) { + $url['scheme'] = $url['scheme'] . '://'; + } + + // Opções do método + if (isset($options['absolute'])) { + $url['scheme'] = $url['scheme'] != '' ? $url['scheme'] : $this->_schemeUrl; + $url['host'] = $url['host'] != '' ? $url['host'] : $this->_baseUrl . '/'; + } + + if (isset($options['query'])) { + $url['query'] = '?' . http_build_query($options['query']); + } + if (isset($options['fragment'])) { + $url['fragment'] = '#' . (string) $options['fragment']; } - } + + // Remove da URL final os componentes que tem valor maior que o especificado + // por 'components'. + if (isset($options['components'])) { + foreach ($this->_components as $key => $value) { + if ($value > $options['components']) { + unset($url[$key]); + } + } + } + + return implode('', $url); } - return implode('', $url); - } - - /** - * Retorna um link HTML simples. Interface externa. - * - * @param string $text O texto a ser apresentado como link HTML - * @param string $path O caminho relativo ou absoluto da URL do link - * @param array $options Opções para gerar a URL do link - * @return string - */ - public static function l($text, $path, array $options = array()) - { - $instance = self::getInstance(); - return $instance->_link($text, $path, $options); - } - - /** - * Retorna um link HTML simples. - * - * @param string $text O texto a ser apresentado como link HTML - * @param string $path O caminho relativo ou absoluto da URL do link - * @param array $options Opções para gerar a URL do link - * @return string - */ - protected function _link($text, $path, array $options = array()) - { - return sprintf('%s', self::url($path, $options), $text); - } + /** + * Retorna um link HTML simples. Interface externa. + * + * @param string $text O texto a ser apresentado como link HTML + * @param string $path O caminho relativo ou absoluto da URL do link + * @param array $options Opções para gerar a URL do link + * + * @return string + */ + public static function l($text, $path, array $options = []) + { + $instance = self::getInstance(); + + return $instance->_link($text, $path, $options); + } + + /** + * Retorna um link HTML simples. + * + * @param string $text O texto a ser apresentado como link HTML + * @param string $path O caminho relativo ou absoluto da URL do link + * @param array $options Opções para gerar a URL do link + * + * @return string + */ + protected function _link($text, $path, array $options = []) + { + return sprintf('%s', self::url($path, $options), $text); + } } diff --git a/ieducar/lib/Portabilis/Array/Utils.php b/ieducar/lib/Portabilis/Array/Utils.php index 01a227bab7..7688f0fc0a 100644 --- a/ieducar/lib/Portabilis/Array/Utils.php +++ b/ieducar/lib/Portabilis/Array/Utils.php @@ -1,219 +1,217 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * Portabilis_Array_Utils class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Array_Utils { - - /* Mescla $defaultArray com $array, - preservando os valores de $array nos casos em que ambos tem a mesma chave. */ - public static function merge($array, $defaultArray) { - foreach($array as $key => $value) { - $defaultArray[$key] = $value; +class Portabilis_Array_Utils +{ + /** + * Mescla $defaultArray com $array, preservando os valores de $array nos + * casos em que ambos tem a mesma chave. + */ + public static function merge($array, $defaultArray) + { + foreach ($array as $key => $value) { + $defaultArray[$key] = $value; + } + + return $defaultArray; } - return $defaultArray; - } - - - /* Mescla os valores de diferentes arrays, onde no array mesclado, cada valor (unico), - passa a ser a chave do array. - ex: mergeValues(array(array(1,2), array(2,3,4)) resulta em array(1=>1, 2=>2, 3=>3, 4=>4) */ - public function mergeValues($arrays) { - if (! is_array($arrays)) - $arrays = array($arrays); - - $merge = array(); - - foreach($arrays as $array) { - foreach($array as $value) { - if (! in_array($value, $merge)) - $merge[$value] = $value; - } + /** + * Mescla os valores de diferentes arrays, onde no array mesclado, cada + * valor (unico), passa a ser a chave do array. + * + * Ex: mergeValues(array(array(1,2), array(2,3,4)) resulta em array(1=>1, 2=>2, 3=>3, 4=>4) + */ + public function mergeValues($arrays) + { + if (!is_array($arrays)) { + $arrays = [$arrays]; + } + + $merge = []; + + foreach ($arrays as $array) { + foreach ($array as $value) { + if (!in_array($value, $merge)) { + $merge[$value] = $value; + } + } + } + + return $merge; } - return $merge; - } - + /** + * Insere uma chave => valor no inicio do $array, preservando os indices + * inteiros dos arrays (sem reiniciar). + */ + public static function insertIn($key, $value, $array) + { + $newArray = [$key => $value]; - /* Insere uma chave => valor no inicio do $array, - preservando os indices inteiros dos arrays (sem reiniciar) */ - public static function insertIn($key, $value, $array) { - $newArray = array($key => $value); + foreach ($array as $key => $value) { + $newArray[$key] = $value; + } - foreach($array as $key => $value) { - $newArray[$key] = $value; + return $newArray; } - return $newArray; - } - - - public static function filterSet($arrays, $attrs = array()){ - if (empty($arrays)) - return array(); - - if (! is_array($arrays)) - $arrays = array($arrays); - - $arraysFiltered = array(); + public static function filterSet($arrays, $attrs = []) + { + if (empty($arrays)) { + return []; + } - foreach($arrays as $array) - $arraysFiltered[] = self::filter($array, $attrs); + if (!is_array($arrays)) { + $arrays = [$arrays]; + } - return $arraysFiltered; - } + $arraysFiltered = []; + foreach ($arrays as $array) { + $arraysFiltered[] = self::filter($array, $attrs); + } - /* Retorna um array {key => value, key => value} - de atributos filtrados de um outro array, podendo renomear nome dos attrs, - util para filtrar um array a ser retornado por uma api - - $arrays - array a ser(em) filtrado(s) - $attrs - atributo ou array de atributos para filtrar objeto, - ex: $attrs = array('cod_escola' => 'id', 'nome') - */ - public static function filter($array, $attrs = array()){ - if (! is_array($attrs)) - $attrs = array($attrs); - - $arrayFiltered = array(); - - // apply filter - foreach($attrs as $attrName => $attrValueName) { - if (! is_string($attrName)) - $attrName = $attrValueName; - - $arrayFiltered[$attrValueName] = $array[$attrName]; + return $arraysFiltered; } - return $arrayFiltered; - } - - - /* transforma um conjunto de arrays "chave => valor, chave => valor" em um array "id => value", - ex: (('id' => 1, 'nome' => 'lucas'), ('id' => 2, 'nome' => 'davila')) - é transformado em (1 => 'lucas', 2 => davila), - - caso uma mesma chave se repita em mais de um array, - será mantido a chave => valor do ultimo array que a contem. - - o array retornado, será ordenado por valor. - */ - public static function setAsIdValue($arrays, $keyAttr, $valueAtt) { - if (empty($arrays)) - return array(); - - if (! is_array($arrays)) - $arrays = array($arrays); - - $idValueArray = array(); - - foreach ($arrays as $array) - $idValueArray = self::merge($idValueArray, self::asIdValue($array, $keyAttr, $valueAtt)); - - return Portabilis_Array_Utils::sortByValue($idValueArray); - } - - - /* transforma um array "chave => valor, chave => valor" em um array "id => value", - ex: ('id' => 1, 'nome' => 'lucas') é transformado em (1 => 'lucas') */ - public static function asIdValue($array, $keyAttr, $valueAtt) { - return array($array[$keyAttr] => $array[$valueAtt]); - } - - - /* ordena array por uma chave usando função php usort, ex: - $ordenedResources = Portabilis_Array_Utils::sortByKey($resources, 'resource_att_name'); */ - public static function sortByKey($key, $array) { - usort($array, function ($a, $b) use ($key) { - return Portabilis_Array_Utils::_keySorter($key, $a, $b); - }); - - return $array; - } + /** + * Retorna um array {key => value, key => value} de atributos filtrados de + * um outro array, podendo renomear nome dos attrs, util para filtrar um + * array a ser retornado por uma api + * + * $arrays - array a ser(em) filtrado(s) + * $attrs - atributo ou array de atributos para filtrar objeto + * + * Ex: $attrs = array('cod_escola' => 'id', 'nome') + */ + public static function filter($array, $attrs = []) + { + if (!is_array($attrs)) { + $attrs = [$attrs]; + } + + $arrayFiltered = []; + + // apply filter + foreach ($attrs as $attrName => $attrValueName) { + if (!is_string($attrName)) { + $attrName = $attrValueName; + } + + $arrayFiltered[$attrValueName] = $array[$attrName]; + } + + return $arrayFiltered; + } - /* ordena array por valor mantendo as chaves associativas, usando função php uasort. */ - public static function sortByValue($array) { - uasort($array, function ($a, $b) { - return Portabilis_Array_Utils::_valueSorter($a, $b); - }); + /** + * Transforma um conjunto de arrays "chave => valor, chave => valor" em um array "id => value", + * + * Ex: (('id' => 1, 'nome' => 'lucas'), ('id' => 2, 'nome' => 'davila')) é + * transformado em (1 => 'lucas', 2 => davila), caso uma mesma chave se + * repita em mais de um array, será mantido a chave => valor do ultimo + * array que a contem. O array retornado, será ordenado por valor. + */ + public static function setAsIdValue($arrays, $keyAttr, $valueAtt) + { + if (empty($arrays)) { + return []; + } + + if (!is_array($arrays)) { + $arrays = [$arrays]; + } + + $idValueArray = []; + + foreach ($arrays as $array) { + $idValueArray = self::merge($idValueArray, self::asIdValue($array, $keyAttr, $valueAtt)); + } + + return Portabilis_Array_Utils::sortByValue($idValueArray); + } - return $array; - } + /** + * Transforma um array "chave => valor, chave => valor" em um array "id => value", + * + * Ex: ('id' => 1, 'nome' => 'lucas') é transformado em (1 => 'lucas') + */ + public static function asIdValue($array, $keyAttr, $valueAtt) + { + return [$array[$keyAttr] => $array[$valueAtt]]; + } - public static function _keySorter($key, $array, $otherArray) { - $a = $array[$key]; - $b = $otherArray[$key]; + /** + * Ordena array por uma chave usando função php usort, + * + * Ex: $ordenedResources = Portabilis_Array_Utils::sortByKey($resources, 'resource_att_name'); + */ + public static function sortByKey($key, $array) + { + usort($array, function ($a, $b) use ($key) { + return Portabilis_Array_Utils::_keySorter($key, $a, $b); + }); + + return $array; + } - if ($a == $b) - return 0; + /** + * Ordena array por valor mantendo as chaves associativas, usando função php uasort. + */ + public static function sortByValue($array) + { + uasort($array, function ($a, $b) { + return Portabilis_Array_Utils::_valueSorter($a, $b); + }); - return ($a < $b) ? -1 : 1; - } + return $array; + } - public static function _valueSorter($a, $b) { - if (is_string($a)) - $a = Portabilis_String_Utils::unaccent($a); + public static function _keySorter($key, $array, $otherArray) + { + $a = $array[$key]; + $b = $otherArray[$key]; - if (is_string($b)) - $b = Portabilis_String_Utils::unaccent($b); + if ($a == $b) { + return 0; + } - if ($a == $b) - return 0; + return ($a < $b) ? -1 : 1; + } - return ($a < $b) ? -1 : 1; - } + public static function _valueSorter($a, $b) + { + if (is_string($a)) { + $a = Portabilis_String_Utils::unaccent($a); + } - /* trim values for a given array */ - public static function trim($array) { + if (is_string($b)) { + $b = Portabilis_String_Utils::unaccent($b); + } - foreach ($array as $i => $v) - $array[$i] = trim($v); + if ($a == $b) { + return 0; + } - return $array; - } + return ($a < $b) ? -1 : 1; + } - public static function arrayColumn($array, $column) { + /** + * Trim values for a given array + */ + public static function trim($array) + { + foreach ($array as $i => $v) { + $array[$i] = trim($v); + } - return array_map(function($val) use ($column) { - return $val[$column]; - },$array); + return $array; + } - } + public static function arrayColumn($array, $column) + { + return array_map(function ($val) use ($column) { + return $val[$column]; + }, $array); + } } diff --git a/ieducar/lib/Portabilis/Business/Professor.php b/ieducar/lib/Portabilis/Business/Professor.php index ac518ce607..752637a7a6 100644 --- a/ieducar/lib/Portabilis/Business/Professor.php +++ b/ieducar/lib/Portabilis/Business/Professor.php @@ -1,241 +1,355 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'include/pmieducar/clsPmieducarServidorAlocacao.inc.php'; -/** - * Portabilis_Business_Professor class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Business_Professor { - - public static function isProfessor($instituicaoId, $userId) { - if(is_numeric($instituicaoId)){ - $sql = "select funcao.professor from pmieducar.servidor_funcao, pmieducar.funcao - where funcao.cod_funcao = servidor_funcao.ref_cod_funcao and funcao.professor = 1 and - servidor_funcao.ref_ref_cod_instituicao = $1 and servidor_funcao.ref_cod_servidor = $2"; - $options = array('params' => array($instituicaoId, $userId), 'return_only' => 'first-field'); - }else{ - $sql = "select funcao.professor from pmieducar.servidor_funcao, pmieducar.funcao - where funcao.cod_funcao = servidor_funcao.ref_cod_funcao and funcao.professor = 1 and - servidor_funcao.ref_cod_servidor = $1"; - $options = array('params' => array($userId), 'return_only' => 'first-field'); +class Portabilis_Business_Professor +{ + public static function isProfessor($instituicaoId, $userId) + { + if (is_numeric($instituicaoId)) { + $sql = ' + select funcao.professor + from pmieducar.servidor_funcao, pmieducar.funcao + where funcao.cod_funcao = servidor_funcao.ref_cod_funcao + and funcao.professor = 1 + and servidor_funcao.ref_ref_cod_instituicao = $1 + and servidor_funcao.ref_cod_servidor = $2 + '; + + $options = ['params' => [$instituicaoId, $userId], 'return_only' => 'first-field']; + } else { + $sql = ' + select funcao.professor + from pmieducar.servidor_funcao, pmieducar.funcao + where funcao.cod_funcao = servidor_funcao.ref_cod_funcao + and funcao.professor = 1 + and servidor_funcao.ref_cod_servidor = $1 + '; + + $options = ['params' => [$userId], 'return_only' => 'first-field']; + } + + return self::fetchPreparedQuery($sql, $options) == '1'; } - return self::fetchPreparedQuery($sql, $options) == '1'; - } - - - public static function escolasAlocado($instituicaoId, $userId) { - if (self::necessarioVinculoTurma($instituicaoId)){ - $sql = "SELECT e.cod_escola as id, - (select juridica.fantasia from pmieducar.escola, cadastro.juridica - where cod_escola = e.cod_escola and escola.ref_idpes = juridica.idpes limit 1) as nome, - ref_servidor as servidor_id, - e.ref_cod_instituicao AS instituicao_id - - FROM pmieducar.quadro_horario qh - INNER JOIN pmieducar.quadro_horario_horarios qhh ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) - INNER JOIN pmieducar.escola e ON (e.cod_escola = qhh.ref_cod_escola) - WHERE e.ref_cod_instituicao = $1 - AND qhh.ref_servidor = $2 - AND qh.ativo = 1 - AND qhh.ativo = 1 - ORDER BY nome"; - - }else{ - $sql = "select ref_cod_escola as id, ref_cod_servidor as servidor_id, ref_ref_cod_instituicao as - instituicao_id, (select juridica.fantasia from escola, cadastro.juridica - where cod_escola = ref_cod_escola and escola.ref_idpes = juridica.idpes limit 1 - ) as nome, carga_horaria, periodo, hora_final, hora_inicial, dia_semana - from pmieducar.servidor_alocacao where ref_ref_cod_instituicao = $1 and ref_cod_servidor = $2 - and ativo = 1"; + public static function escolasAlocado($instituicaoId, $userId) + { + if (self::necessarioVinculoTurma($instituicaoId)) { + $sql = ' + SELECT + e.cod_escola as id, + ( + select juridica.fantasia + from pmieducar.escola, cadastro.juridica + where cod_escola = e.cod_escola + and escola.ref_idpes = juridica.idpes limit 1 + ) as nome, + ref_servidor as servidor_id, + e.ref_cod_instituicao AS instituicao_id + FROM pmieducar.quadro_horario qh + INNER JOIN pmieducar.quadro_horario_horarios qhh + ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) + INNER JOIN pmieducar.escola e + ON (e.cod_escola = qhh.ref_cod_escola) + WHERE e.ref_cod_instituicao = $1 + AND qhh.ref_servidor = $2 + AND qh.ativo = 1 + AND qhh.ativo = 1 + ORDER BY nome + '; + } else { + $sql = ' + select + ref_cod_escola as id, + ref_cod_servidor as servidor_id, + ref_ref_cod_instituicao as instituicao_id, + ( + select juridica.fantasia + from escola, cadastro.juridica + where cod_escola = ref_cod_escola + and escola.ref_idpes = juridica.idpes + limit 1 + ) as nome, + carga_horaria, + periodo, + hora_final, + hora_inicial, + dia_semana + from pmieducar.servidor_alocacao + where ref_ref_cod_instituicao = $1 + and ref_cod_servidor = $2 + and ativo = 1 + '; + } + + $options = ['params' => [$instituicaoId, $userId]]; + + return self::fetchPreparedQuery($sql, $options); } - $options = array('params' => array($instituicaoId, $userId)); - return self::fetchPreparedQuery($sql, $options); - } - - - public static function cursosAlocado($instituicaoId, $escolaId, $userId){ - if (self::necessarioVinculoTurma($instituicaoId)){ - $sql = "SELECT c.cod_curso as id, c.nm_curso as nome + public static function cursosAlocado($instituicaoId, $escolaId, $userId) + { + if (self::necessarioVinculoTurma($instituicaoId)) { + $sql = ' + SELECT + c.cod_curso as id, + c.nm_curso as nome FROM pmieducar.quadro_horario qh - INNER JOIN pmieducar.quadro_horario_horarios qhh ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) - INNER JOIN pmieducar.turma t ON (t.cod_turma = qh.ref_cod_turma) - INNER JOIN pmieducar.serie s ON (t.ref_ref_cod_serie = s.cod_serie) - INNER JOIN pmieducar.curso c ON (c.cod_curso = s.ref_cod_curso) + INNER JOIN pmieducar.quadro_horario_horarios qhh + ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) + INNER JOIN pmieducar.turma t + ON (t.cod_turma = qh.ref_cod_turma) + INNER JOIN pmieducar.serie s + ON (t.ref_ref_cod_serie = s.cod_serie) + INNER JOIN pmieducar.curso c + ON (c.cod_curso = s.ref_cod_curso) WHERE qhh.ref_cod_escola = $1 AND qhh.ref_servidor = $2 AND qhh.ativo = 1 AND qh.ativo = 1 - ORDER BY c.nm_curso"; - $options = array('params' => array($escolaId, $userId)); - }else{ - $sql = "select cod_curso as id, nm_curso as nome from pmieducar.servidor_curso_ministra, - pmieducar.curso, pmieducar.escola_curso, pmieducar.escola - where escola.ref_cod_instituicao = $1 and escola.cod_escola = $2 - and escola_curso.ref_cod_curso = cod_curso and escola_curso.ref_cod_escola = cod_escola - and servidor_curso_ministra.ref_cod_curso = curso.cod_curso and ref_cod_servidor = $3"; - $options = array('params' => array($instituicaoId, $escolaId, $userId)); + ORDER BY c.nm_curso + '; + + $options = ['params' => [$escolaId, $userId]]; + } else { + $sql = ' + select + cod_curso as id, + nm_curso as nome + from + pmieducar.servidor_curso_ministra, + pmieducar.curso, + pmieducar.escola_curso, + pmieducar.escola + where escola.ref_cod_instituicao = $1 + and escola.cod_escola = $2 + and escola_curso.ref_cod_curso = cod_curso + and escola_curso.ref_cod_escola = cod_escola + and servidor_curso_ministra.ref_cod_curso = curso.cod_curso + and ref_cod_servidor = $3 + '; + + $options = ['params' => [$instituicaoId, $escolaId, $userId]]; + } + + return self::fetchPreparedQuery($sql, $options); } - - return self::fetchPreparedQuery($sql, $options); - } - - public static function seriesAlocado($instituicaoId, $escolaId, $cursoId, $userId) { - $instituicaoId = $instituicaoId ?: 0; - $escolaId = $escolaId ?: 0; - $cursoId = $cursoId ?: 0; - - if (self::canLoadSeriesAlocado($instituicaoId)){ - $sql = "SELECT s.cod_serie as id, s.nm_serie as nome - FROM pmieducar.quadro_horario qh - INNER JOIN pmieducar.quadro_horario_horarios qhh ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) - INNER JOIN pmieducar.turma t ON (t.cod_turma = qh.ref_cod_turma) - INNER JOIN pmieducar.serie s ON (t.ref_ref_cod_serie = s.cod_serie) - INNER JOIN pmieducar.escola e ON (e.cod_escola = qhh.ref_cod_escola) - WHERE e.ref_cod_instituicao = $1 - AND e.cod_escola = $2 - AND s.ref_cod_curso = $3 - AND qhh.ref_servidor = $4 - ORDER BY s.nm_serie"; - return self::fetchPreparedQuery($sql, array('params' => array($instituicaoId, $escolaId, $cursoId, $userId) )); + + public static function seriesAlocado($instituicaoId, $escolaId, $cursoId, $userId) + { + $instituicaoId = $instituicaoId ?: 0; + $escolaId = $escolaId ?: 0; + $cursoId = $cursoId ?: 0; + + if (self::canLoadSeriesAlocado($instituicaoId)) { + $sql = ' + SELECT + s.cod_serie as id, + s.nm_serie as nome + FROM pmieducar.quadro_horario qh + INNER JOIN pmieducar.quadro_horario_horarios qhh + ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) + INNER JOIN pmieducar.turma t + ON (t.cod_turma = qh.ref_cod_turma) + INNER JOIN pmieducar.serie s + ON (t.ref_ref_cod_serie = s.cod_serie) + INNER JOIN pmieducar.escola e + ON (e.cod_escola = qhh.ref_cod_escola) + WHERE e.ref_cod_instituicao = $1 + AND e.cod_escola = $2 + AND s.ref_cod_curso = $3 + AND qhh.ref_servidor = $4 + ORDER BY s.nm_serie + '; + + return self::fetchPreparedQuery($sql, ['params' => [$instituicaoId, $escolaId, $cursoId, $userId]]); + } } - } - public static function canLoadSeriesAlocado($instituicaoId){ - return self::necessarioVinculoTurma($instituicaoId); - } + public static function canLoadSeriesAlocado($instituicaoId) + { + return self::necessarioVinculoTurma($instituicaoId); + } - public static function turmasAlocado($instituicaoId, $escolaId, $serieId, $userId) { - if (self::necessarioVinculoTurma($instituicaoId)){ - $sql = "SELECT cod_turma as id, nm_turma as nome, t.ano + public static function turmasAlocado($instituicaoId, $escolaId, $serieId, $userId) + { + if (self::necessarioVinculoTurma($instituicaoId)) { + $sql = ' + SELECT + cod_turma as id, + nm_turma as nome, + t.ano FROM pmieducar.quadro_horario qh - INNER JOIN pmieducar.quadro_horario_horarios qhh ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) - INNER JOIN pmieducar.turma t ON (t.cod_turma = qh.ref_cod_turma) + INNER JOIN pmieducar.quadro_horario_horarios qhh + ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) + INNER JOIN pmieducar.turma t + ON (t.cod_turma = qh.ref_cod_turma) WHERE qhh.ref_cod_escola = $1 AND qhh.ref_cod_serie = $2 AND qhh.ref_servidor = $3 AND qhh.ativo = 1 AND qh.ativo = 1 - ORDER BY t.nm_turma ASC"; - }else{ - # Feito gambiarra para que quando professor tenha alocação liste todas turmas do turno integral - $sql = "SELECT cod_turma as id, nm_turma as nome from pmieducar.turma where ref_ref_cod_escola = $1 - and (ref_ref_cod_serie = $2 or ref_ref_cod_serie_mult = $2) and ativo = 1 and - visivel != 'f' and (turma_turno_id in ( select periodo from servidor_alocacao where - ref_cod_escola = ref_ref_cod_escola and ref_cod_servidor = $3 and ativo = 1) OR ( turma_turno_id = 4 AND (select 1 from servidor_alocacao where - ref_cod_escola = ref_ref_cod_escola and ref_cod_servidor = $3 and ativo = 1 LIMIT 1) IS NOT NULL )) - order by nm_turma asc"; + ORDER BY t.nm_turma ASC + '; + } else { + # Feito gambiarra para que quando professor tenha alocação liste todas turmas do turno integral + $sql = ' + SELECT + cod_turma as id, + nm_turma as nome + from pmieducar.turma + where ref_ref_cod_escola = $1 + and ( + ref_ref_cod_serie = $2 + or ref_ref_cod_serie_mult = $2 + ) + and ativo = 1 + and visivel != \'f\' + and + ( + turma_turno_id in ( + select periodo + from servidor_alocacao + where ref_cod_escola = ref_ref_cod_escola + and ref_cod_servidor = $3 + and ativo = 1 + ) + OR + ( + turma_turno_id = 4 + AND ( + select 1 + from servidor_alocacao + where ref_cod_escola = ref_ref_cod_escola + and ref_cod_servidor = $3 + and ativo = 1 + LIMIT 1 + ) IS NOT NULL + ) + ) + order by nm_turma asc + '; + } + + return self::fetchPreparedQuery($sql, ['params' => [$escolaId, $serieId, $userId]]); } - return self::fetchPreparedQuery($sql, array('params' => array($escolaId, $serieId, $userId))); - } - - - public static function componentesCurricularesAlocado($instituicaoId, $turmaId, $anoLetivo, $userId) { - if (self::necessarioVinculoTurma($instituicaoId)){ - $sql = "SELECT cc.id, cc.nome, ac.nome as area_conhecimento, ac.secao as secao_area_conhecimento + public static function componentesCurricularesAlocado($instituicaoId, $turmaId, $anoLetivo, $userId) + { + if (self::necessarioVinculoTurma($instituicaoId)) { + $sql = ' + SELECT + cc.id, cc.nome, + ac.nome as area_conhecimento, + ac.secao as secao_area_conhecimento FROM pmieducar.quadro_horario qh - INNER JOIN pmieducar.quadro_horario_horarios qhh ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) - INNER JOIN modules.componente_curricular cc ON (cc.id = qhh.ref_cod_disciplina) - INNER JOIN modules.area_conhecimento ac ON (cc.area_conhecimento_id = ac.id) + INNER JOIN pmieducar.quadro_horario_horarios qhh + ON (qh.cod_quadro_horario = qhh.ref_cod_quadro_horario) + INNER JOIN modules.componente_curricular cc + ON (cc.id = qhh.ref_cod_disciplina) + INNER JOIN modules.area_conhecimento ac + ON (cc.area_conhecimento_id = ac.id) WHERE qh.ref_cod_turma = $1 AND qhh.ref_servidor = $2 AND qhh.ativo = 1 AND qh.ativo = 1 - ORDER BY ac.secao, ac.nome, cc.nome"; - $componentes = self::fetchPreparedQuery($sql, array('params' => array($turmaId, $userId))); - }else{ - $componentes = self::componentesCurricularesTurmaAlocado($turmaId, $anoLetivo, $userId); - - if (empty($componentes)) - $componentes = self::componentesCurricularesCursoAlocado($turmaId, $anoLetivo, $userId); - } - return $componentes; - } - - - protected static function componentesCurricularesTurmaAlocado($turmaId, $anoLetivo, $userId) { - $sql = "select cc.id, cc.nome, ac.nome as area_conhecimento, ac.secao as secao_area_conhecimento - from modules.componente_curricular_turma as cct, pmieducar.turma, modules.componente_curricular as cc, modules.area_conhecimento as ac, - pmieducar.escola_ano_letivo as al, pmieducar.servidor_disciplina as scc - where turma.cod_turma = $1 and cct.turma_id = turma.cod_turma and cct.escola_id = turma.ref_ref_cod_escola - and cct.componente_curricular_id = cc.id and al.ano = $2 and cct.escola_id = al.ref_cod_escola and - scc.ref_ref_cod_instituicao = turma.ref_cod_instituicao and scc.ref_cod_servidor = $3 and - scc.ref_cod_curso = turma.ref_cod_curso and scc.ref_cod_disciplina = cc.id and cc.area_conhecimento_id = ac.id - order by ac.secao, ac.nome, cc.nome"; - - $options = array('params' => array($turmaId, $anoLetivo, $userId)); - - return self::fetchPreparedQuery($sql, $options); - } + ORDER BY ac.secao, ac.nome, cc.nome + '; + $componentes = self::fetchPreparedQuery($sql, ['params' => [$turmaId, $userId]]); + } else { + $componentes = self::componentesCurricularesTurmaAlocado($turmaId, $anoLetivo, $userId); - protected static function componentesCurricularesCursoAlocado($turmaId, $anoLetivo, $userId) { - $sql = "select cc.id as id, cc.nome as nome, ac.nome as area_conhecimento, ac.secao as secao_area_conhecimento from pmieducar.serie, pmieducar.escola_serie_disciplina as esd, - pmieducar.turma, modules.componente_curricular as cc, modules.area_conhecimento as ac, pmieducar.escola_ano_letivo as al, - pmieducar.servidor_disciplina as scc where turma.cod_turma = $1 and serie.cod_serie = - turma.ref_ref_cod_serie and esd.ref_ref_cod_escola = turma.ref_ref_cod_escola and esd.ref_ref_cod_serie = - serie.cod_serie and esd.ref_cod_disciplina = cc.id and al.ano = $2 and esd.ref_ref_cod_escola = - al.ref_cod_escola and serie.ativo = 1 and esd.ativo = 1 and al.ativo = 1 and scc.ref_ref_cod_instituicao = - turma.ref_cod_instituicao and scc.ref_cod_servidor = $3 and scc.ref_cod_curso = serie.ref_cod_curso and - scc.ref_cod_disciplina = cc.id and cc.area_conhecimento_id = ac.id - order by ac.secao, ac.nome, cc.nome"; + if (empty($componentes)) { + $componentes = self::componentesCurricularesCursoAlocado($turmaId, $anoLetivo, $userId); + } + } - $options = array('params' => array($turmaId, $anoLetivo, $userId)); - - return self::fetchPreparedQuery($sql, $options); - } + return $componentes; + } + protected static function componentesCurricularesTurmaAlocado($turmaId, $anoLetivo, $userId) + { + $sql = ' + select + cc.id, + cc.nome, + ac.nome as area_conhecimento, + ac.secao as secao_area_conhecimento + from + modules.componente_curricular_turma as cct, + pmieducar.turma, + modules.componente_curricular as cc, + modules.area_conhecimento as ac, + pmieducar.escola_ano_letivo as al, + pmieducar.servidor_disciplina as scc + where turma.cod_turma = $1 + and cct.turma_id = turma.cod_turma + and cct.escola_id = turma.ref_ref_cod_escola + and cct.componente_curricular_id = cc.id + and al.ano = $2 + and cct.escola_id = al.ref_cod_escola + and scc.ref_ref_cod_instituicao = turma.ref_cod_instituicao + and scc.ref_cod_servidor = $3 + and scc.ref_cod_curso = turma.ref_cod_curso + and scc.ref_cod_disciplina = cc.id + and cc.area_conhecimento_id = ac.id + order by ac.secao, ac.nome, cc.nome + '; + + $options = ['params' => [$turmaId, $anoLetivo, $userId]]; + + return self::fetchPreparedQuery($sql, $options); + } - /*public static function alocacoes($instituicaoId, $escolaId, $userId) { - $alocacoes = new ClsPmieducarServidorAlocacao(); - return $alocacoes->lista(null, $instituicaoId, null, null, $escolaId, $userId); - }*/ + protected static function componentesCurricularesCursoAlocado($turmaId, $anoLetivo, $userId) + { + $sql = ' + select + cc.id as id, + cc.nome as nome, + ac.nome as area_conhecimento, + ac.secao as secao_area_conhecimento + from + pmieducar.serie, + pmieducar.escola_serie_disciplina as esd, + pmieducar.turma, + modules.componente_curricular as cc, + modules.area_conhecimento as ac, + pmieducar.escola_ano_letivo as al, + pmieducar.servidor_disciplina as scc + where turma.cod_turma = $1 + and serie.cod_serie = turma.ref_ref_cod_serie + and esd.ref_ref_cod_escola = turma.ref_ref_cod_escola + and esd.ref_ref_cod_serie = serie.cod_serie + and esd.ref_cod_disciplina = cc.id + and al.ano = $2 + and esd.ref_ref_cod_escola = al.ref_cod_escola + and serie.ativo = 1 + and esd.ativo = 1 + and al.ativo = 1 + and scc.ref_ref_cod_instituicao = turma.ref_cod_instituicao + and scc.ref_cod_servidor = $3 + and scc.ref_cod_curso = serie.ref_cod_curso + and scc.ref_cod_disciplina = cc.id + and cc.area_conhecimento_id = ac.id + order by ac.secao, ac.nome, cc.nome + '; + + $options = ['params' => [$turmaId, $anoLetivo, $userId]]; + + return self::fetchPreparedQuery($sql, $options); + } - // wrappers for Portabilis*Utils* + protected static function fetchPreparedQuery($sql, $options = []) + { + return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + } - protected static function fetchPreparedQuery($sql, $options = array()) { - return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - } + private static function necessarioVinculoTurma($instituicaoId) + { + $sql = 'SELECT exigir_vinculo_turma_professor FROM pmieducar.instituicao WHERE cod_instituicao = $1'; - private static function necessarioVinculoTurma($instituicaoId){ - $sql = "SELECT exigir_vinculo_turma_professor FROM pmieducar.instituicao WHERE cod_instituicao = $1"; - return self::fetchPreparedQuery($sql, array('params' => array($instituicaoId), 'return_only' => 'first-field')) == 1; - } -} \ No newline at end of file + return self::fetchPreparedQuery($sql, ['params' => [$instituicaoId], 'return_only' => 'first-field']) == 1; + } +} diff --git a/ieducar/lib/Portabilis/Controller/ApiCoreController.php b/ieducar/lib/Portabilis/Controller/ApiCoreController.php index b3d42e8a09..228c4cfb96 100644 --- a/ieducar/lib/Portabilis/Controller/ApiCoreController.php +++ b/ieducar/lib/Portabilis/Controller/ApiCoreController.php @@ -1,42 +1,8 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @subpackage lib - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ - require_once 'include/clsBanco.inc.php'; - require_once 'Core/Controller/Page/EditController.php'; require_once 'CoreExt/Exception.php'; - require_once 'lib/Portabilis/Messenger.php'; require_once 'lib/Portabilis/Validator.php'; require_once 'lib/Portabilis/DataMapper/Utils.php'; @@ -48,543 +14,562 @@ class ApiCoreController extends Core_Controller_Page_EditController { + // variaveis usadas apenas em formulários, desnecesário subescrever nos filhos. - // variaveis usadas apenas em formulários, desnecesário subescrever nos filhos. + protected $_saveOption = false; - protected $_saveOption = FALSE; - protected $_deleteOption = FALSE; - protected $_titulo = ''; + protected $_deleteOption = false; + protected $_titulo = ''; - // adicionar classe do data mapper que se deseja usar, em tais casos. - protected $_dataMapper = null; + // adicionar classe do data mapper que se deseja usar, em tais casos. + protected $_dataMapper = null; - /* Variaveis utilizadas pelos validadores validatesAuthorizationToDestroy e validatesAuthorizationToChange. - Notar que todos usuários tem autorização para o processo 0, - nos controladores em que se deseja verificar permissões, adicionar o processo AP da funcionalidade. - */ - protected $_processoAp = 0; - protected $_nivelAcessoOption = App_Model_NivelAcesso::INSTITUCIONAL; + // Variaveis utilizadas pelos validadores validatesAuthorizationToDestroy + // e validatesAuthorizationToChange. + // Notar que todos usuários tem autorização para o processo 0, nos + // controladores em que se deseja verificar permissões, adicionar o + // processo AP da funcionalidade. + protected $_processoAp = 0; - public function __construct() { - $this->messenger = new Portabilis_Messenger(); - $this->validator = new Portabilis_Validator($this->messenger); - $this->response = array(); - } + protected $_nivelAcessoOption = App_Model_NivelAcesso::INSTITUCIONAL; - protected function currentUser() { - return Portabilis_Utils_User::load($this->getSession()->id_pessoa); - } + public function __construct() + { + $this->messenger = new Portabilis_Messenger(); + $this->validator = new Portabilis_Validator($this->messenger); + $this->response = []; + } - protected function getNivelAcesso() { - return Portabilis_Utils_User::getNivelAcesso(); - } + protected function currentUser() + { + return Portabilis_Utils_User::load($this->getSession()->id_pessoa); + } + protected function getNivelAcesso() + { + return Portabilis_Utils_User::getNivelAcesso(); + } - // validators + protected function validatesAccessKey() + { + $valid = false; - protected function validatesAccessKey() { - $valid = false; + if (!is_null($this->getRequest()->access_key)) { + $accessKey = $GLOBALS['coreExt']['Config']->apis->access_key; + $valid = $accessKey == $this->getRequest()->access_key; - if (! is_null($this->getRequest()->access_key)) { - $accessKey = $GLOBALS['coreExt']['Config']->apis->access_key; - $valid = $accessKey == $this->getRequest()->access_key; + if (!$valid) { + $this->messenger->append('Chave de acesso inválida!'); + } + } - if (! $valid) - $this->messenger->append('Chave de acesso inválida!'); + return $valid; } - return $valid; - } + protected function validatesSignature() + { + // #TODO implementar validação urls assinadas + return true; + } - protected function validatesSignature() { - // #TODO implementar validação urls assinadas - return true; - } + protected function validatesUserIsLoggedIn() + { + $canAccess = is_numeric($this->getSession()->id_pessoa); - protected function validatesUserIsLoggedIn(){ - $canAccess = is_numeric($this->getSession()->id_pessoa); + if (!$canAccess) { + $canAccess = ($this->validatesAccessKey() && $this->validatesSignature()); + } - if (! $canAccess) - $canAccess = ($this->validatesAccessKey() && $this->validatesSignature()); + if (!$canAccess) { + $msg = 'Usuário deve estar logado ou a chave de acesso deve ser enviada!'; + $this->messenger->append($msg, 'error', $encodeToUtf8 = false, $ignoreIfHasMsgWithType = 'error'); + } - if (! $canAccess) { - $msg = 'Usuário deve estar logado ou a chave de acesso deve ser enviada!'; - $this->messenger->append($msg, 'error', $encodeToUtf8 = false, $ignoreIfHasMsgWithType = 'error'); + return $canAccess; } - return $canAccess; - } + protected function validatesUserIsAdmin() + { + $user = $this->currentUser(); + if (!$user['super']) { + $this->messenger->append('O usuário logado deve ser o admin'); - protected function validatesUserIsAdmin() { - $user = $this->currentUser(); + return false; + } - if(! $user['super']) { - $this->messenger->append("O usuário logado deve ser o admin"); - return false; + return true; } - return true; - } - - protected function validatesId($resourceName, $options = array()) { - $attrName = $resourceName . ($resourceName ? '_id' : 'id'); + protected function validatesId($resourceName, $options = []) + { + $attrName = $resourceName . ($resourceName ? '_id' : 'id'); - return $this->validatesPresenceOf($attrName) && + return $this->validatesPresenceOf($attrName) && $this->validatesExistenceOf($resourceName, $this->getRequest()->$attrName, $options); - } - - // subescrever nos controladores cujo recurso difere do padrao (schema pmieducar, tabela , pk cod_) - protected function validatesResourceId() { - return $this->validatesPresenceOf('id') && - $this->validatesExistenceOf($this->getRequest()->resource, $this->getRequest()->id); - } - - protected function validatesAuthorizationToDestroy() { - $can = $this->getClsPermissoes()->permissao_excluir($this->getBaseProcessoAp(), - $this->getSession()->id_pessoa, - $this->_nivelAcessoOption); - - if (! $can) - $this->messenger->append("Usuário sem permissão para excluir '{$this->getRequest()->resource}'."); + } - return $can; - } + protected function validatesResourceId() + { + return $this->validatesPresenceOf('id') + && $this->validatesExistenceOf($this->getRequest()->resource, $this->getRequest()->id); + } - protected function validatesAuthorizationToChange() { - $can = $this->getClsPermissoes()->permissao_cadastra($this->getBaseProcessoAp(), - $this->getSession()->id_pessoa, - $this->_nivelAcessoOption); + protected function validatesAuthorizationToDestroy() + { + $can = $this->getClsPermissoes()->permissao_excluir( + $this->getBaseProcessoAp(), + $this->getSession()->id_pessoa, + $this->_nivelAcessoOption + ); - if (! $can) - $this->messenger->append("Usuário sem permissão para cadastrar '{$this->getRequest()->resource}'."); + if (!$can) { + $this->messenger->append("Usuário sem permissão para excluir '{$this->getRequest()->resource}'."); + } - return $can; - } + return $can; + } + protected function validatesAuthorizationToChange() + { + $can = $this->getClsPermissoes()->permissao_cadastra( + $this->getBaseProcessoAp(), + $this->getSession()->id_pessoa, + $this->_nivelAcessoOption + ); - // validation + if (!$can) { + $this->messenger->append("Usuário sem permissão para cadastrar '{$this->getRequest()->resource}'."); + } - protected function canAcceptRequest() { - return $this->validatesUserIsLoggedIn() && - $this->validatesPresenceOf(array('oper', 'resource')); - } + return $can; + } + protected function canAcceptRequest() + { + return $this->validatesUserIsLoggedIn() + && $this->validatesPresenceOf(['oper', 'resource']); + } - protected function canGet() { - return $this->validatesResourceId(); - } + protected function canGet() + { + return $this->validatesResourceId(); + } + protected function canChange() + { + throw new Exception('canChange must be overwritten!'); + } - protected function canChange() { - throw new Exception('canChange must be overwritten!'); - } + protected function canPost() + { + return $this->canChange() + && $this->validatesAuthorizationToChange(); + } + protected function canPut() + { + return $this->canChange() + && $this->validatesResourceId() + && $this->validatesAuthorizationToChange(); + } - protected function canPost() { - return $this->canChange() && - $this->validatesAuthorizationToChange(); - } + protected function canSearch() + { + return $this->validatesPresenceOf('query'); + } + protected function canDelete() + { + return $this->validatesResourceId() + && $this->validatesAuthorizationToDestroy(); + } - protected function canPut() { - return $this->canChange() && - $this->validatesResourceId() && - $this->validatesAuthorizationToChange(); - } + protected function canEnable() + { + return $this->validatesResourceId() + && $this->validatesAuthorizationToChange(); + } + protected function notImplementedOperationError() + { + $this->messenger->append("Operação '{$this->getRequest()->oper}' não implementada para o recurso '{$this->getRequest()->resource}'"); + } - protected function canSearch() { - return $this->validatesPresenceOf('query'); - } + protected function appendResponse($name, $value = '') + { + if (is_array($name)) { + foreach ($name as $k => $v) { + $this->response[$k] = $v; + } + } elseif (!is_null($name)) { + $this->response[$name] = $value; + } + } + protected function getAvailableOperationsForResources() + { + throw new CoreExt_Exception('É necessário sobrescrever o método "getExpectedOperationsForResources()" de ApiCoreController.'); + } - protected function canDelete() { - return $this->validatesResourceId() && - $this->validatesAuthorizationToDestroy(); - } + protected function isRequestFor($oper, $resource) + { + return $this->getRequest()->resource == $resource && + $this->getRequest()->oper == $oper; + } + protected function prepareResponse() + { + try { + if (isset($this->getRequest()->oper)) { + $this->appendResponse('oper', $this->getRequest()->oper); + } - protected function canEnable() { - return $this->validatesResourceId() && - $this->validatesAuthorizationToChange(); - } + if (isset($this->getRequest()->resource)) { + $this->appendResponse('resource', $this->getRequest()->resource); + } + $this->appendResponse('msgs', $this->messenger->getMsgs()); + $this->appendResponse('any_error_msg', $this->messenger->hasMsgWithType('error')); - // api + $response = SafeJson::encode($this->response); + } catch (Exception $e) { + error_log("Erro inesperado no metodo prepareResponse da classe ApiCoreController: {$e->getMessage()}"); - protected function notImplementedOperationError() { - $this->messenger->append("Operação '{$this->getRequest()->oper}' não implementada para o recurso '{$this->getRequest()->resource}'"); - } + $response = [ + 'msgs' => [ + 'msg' => 'Erro inesperado no servidor. Por favor, tente novamente.', + 'type' => 'error' + ] + ]; + $response = SafeJson::encode($response); + } - protected function appendResponse($name, $value = '') { - if (is_array($name)) { - foreach($name as $k => $v) { - $this->response[$k] = $v; - } + echo $response; } - elseif (! is_null($name)) - $this->response[$name] = $value; - } - - - // subscrever nas classes filhas sentando os recursos disponibilizados e operacoes permitidas, ex: - // return array('resources1' => array('get'), 'resouce2' => array('post', 'delete')); - protected function getAvailableOperationsForResources() { - throw new CoreExt_Exception('É necessário sobrescrever o método "getExpectedOperationsForResources()" de ApiCoreController.'); - } - - - protected function isRequestFor($oper, $resource) { - return $this->getRequest()->resource == $resource && - $this->getRequest()->oper == $oper; - } - - protected function prepareResponse(){ - try { - if (isset($this->getRequest()->oper)) - $this->appendResponse('oper', $this->getRequest()->oper); + public function generate(CoreExt_Controller_Page_Interface $instance) + { + header('Content-type: application/json; charset=UTF-8'); - if (isset($this->getRequest()->resource)) - $this->appendResponse('resource', $this->getRequest()->resource); - - $this->appendResponse('msgs', $this->messenger->getMsgs()); - $this->appendResponse('any_error_msg', $this->messenger->hasMsgWithType('error')); + try { + if ($this->canAcceptRequest()) { + $instance->Gerar(); + } + } catch (Exception $e) { + $this->messenger->append('Exception: ' . $e->getMessage(), 'error', $encodeToUtf8 = true); + } - $response = SafeJson::encode($this->response); + echo $this->prepareResponse(); } - catch (Exception $e){ - error_log("Erro inesperado no metodo prepareResponse da classe ApiCoreController: {$e->getMessage()}"); - $response = array('msgs' => array('msg' => 'Erro inesperado no servidor. Por favor, tente novamente.', - 'type' => 'error')); - $response = SafeJson::encode($response); + public function Gerar() + { + throw new CoreExt_Exception('The method \'Gerar\' must be overwritten!'); } - echo $response; - } + protected function validatesPresenceOf($requiredParamNames) + { + if (!is_array($requiredParamNames)) { + $requiredParamNames = [$requiredParamNames]; + } + $valid = true; - public function generate(CoreExt_Controller_Page_Interface $instance){ - header('Content-type: application/json; charset=UTF-8'); + foreach ($requiredParamNames as $param) { + $value = $this->getRequest()->$param; + if (!$this->validator->validatesPresenceOf($value, $param) and $valid) { + $valid = false; + } + } - try { - if ($this->canAcceptRequest()) - $instance->Gerar(); + return $valid; } - catch (Exception $e){ - $this->messenger->append('Exception: ' . $e->getMessage(), 'error', $encodeToUtf8 = true); + + protected function validatesExistenceOf($resourceName, $value, $options = []) + { + $defaultOptions = [ + 'schema_name' => 'pmieducar', + 'field_name' => "cod_{$resourceName}", + 'add_msg_on_error' => true + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + + if (is_array($value)) { + $valid = true; + + foreach ($value as $v) { + $valid = $valid + && $this->validator->validatesValueIsInBd( + $options['field_name'], + $v, + $options['schema_name'], + $resourceName, + $raiseExceptionOnFail = false, + $addMsgOnError = $options['add_msg_on_error'] + ); + } + + return $valid; + } else { + return $this->validator->validatesValueIsInBd( + $options['field_name'], + $value, + $options['schema_name'], + $resourceName, + $raiseExceptionOnFail = false, + $addMsgOnError = $options['add_msg_on_error'] + ); + } } - echo $this->prepareResponse(); - } + protected function validatesUniquenessOf($resourceName, $value, $options = []) + { + $defaultOptions = [ + 'schema_name' => 'pmieducar', + 'field_name' => "cod_{$resourceName}", + 'add_msg_on_error' => true + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + + return $this->validator->validatesValueNotInBd( + $options['field_name'], + $value, + $options['schema_name'], + $resourceName, + $raiseExceptionOnFail = false, + $addMsgOnError = $options['add_msg_on_error'] + ); + } + protected function validatesIsNumeric($expectedNumericParamNames) + { + if (!is_array($expectedNumericParamNames)) { + $expectedNumericParamNames = [$expectedNumericParamNames]; + } - /* subescrever nas classes filhas setando as verificações desejadas e retornando a resposta, - conforme recurso e operação recebida ex: get, post ou delete, ex: + $valid = true; - if ($this->getRequest()->oper == 'get') - { - // caso retorne apenas um recurso - $this->appendResponse('matriculas', $matriculas); + foreach ($requiredParamNames as $param) { + if (!$this->validator->validatesValueIsNumeric($this->getRequest()->$param, $param) and $valid) { + $valid = false; + } + } - // ou para multiplos recursos, pode-se usar o argumento resource - if ($this->getRequest()->resource == 'matriculas') - $this->appendResponse('matriculas', $this->getMatriculas()); - elseif ($this->getRequest()->resource == 'alunos') - $this->appendResponse('alunos', $this->getAlunos); - else - $this->notImplementedError(); - } - elseif ($this->getRequest()->oper == 'post') - $this->postMatricula(); - else - $this->notImplementedError(); - */ - public function Gerar(){ - throw new CoreExt_Exception("The method 'Gerar' must be overwritten!"); - } + return $valid; + } + protected function fetchPreparedQuery($sql, $params = [], $hideExceptions = true, $returnOnly = '') + { + $options = [ + 'params' => $params, + 'show_errors' => !$hideExceptions, + 'return_only' => $returnOnly, + 'messenger' => $this->messenger + ]; - // #TODO mover validadores para classe lib/Portabilis/Validator.php / adicionar wrapper para tais + return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + } - protected function validatesPresenceOf($requiredParamNames) { - if (! is_array($requiredParamNames)) - $requiredParamNames = array($requiredParamNames); + protected function getDataMapperFor($packageName, $modelName) + { + return Portabilis_DataMapper_Utils::getDataMapperFor($packageName, $modelName); + } - $valid = true; + protected function getEntityOf($dataMapper, $id) + { + return $dataMapper->find($id); + } - foreach($requiredParamNames as $param) { - $value = $this->getRequest()->$param; - if (! $this->validator->validatesPresenceOf($value, $param) and $valid) { - $valid = false; - } - } - - return $valid; - } - - - protected function validatesExistenceOf($resourceName, $value, $options = array()) { - $defaultOptions = array('schema_name' => 'pmieducar', - 'field_name' => "cod_{$resourceName}", - 'add_msg_on_error' => true); - - $options = $this->mergeOptions($options, $defaultOptions); - - if (is_array($value)){ - $valid = true; - foreach ($value as $v) { - $valid = $valid && $this->validator->validatesValueIsInBd($options['field_name'], - $v, - $options['schema_name'], - $resourceName, - $raiseExceptionOnFail = false, - $addMsgOnError = $options['add_msg_on_error']); - } - return $valid; - }else - return $this->validator->validatesValueIsInBd($options['field_name'], - $value, - $options['schema_name'], - $resourceName, - $raiseExceptionOnFail = false, - $addMsgOnError = $options['add_msg_on_error']); - } - - protected function validatesUniquenessOf($resourceName, $value, $options = array()) { - $defaultOptions = array('schema_name' => 'pmieducar', - 'field_name' => "cod_{$resourceName}", - 'add_msg_on_error' => true); - - $options = $this->mergeOptions($options, $defaultOptions); - - return $this->validator->validatesValueNotInBd($options['field_name'], - $value, - $options['schema_name'], - $resourceName, - $raiseExceptionOnFail = false, - $addMsgOnError = $options['add_msg_on_error']); - } - - - protected function validatesIsNumeric($expectedNumericParamNames) { - if (! is_array($expectedNumericParamNames)) - $expectedNumericParamNames = array($expectedNumericParamNames); - - $valid = true; - - foreach($requiredParamNames as $param) { - if (! $this->validator->validatesValueIsNumeric($this->getRequest()->$param, $param) and $valid) { - $valid = false; + protected function tryGetEntityOf($dataMapper, $id) + { + try { + $entity = $this->getEntityOf($dataMapper, $id); + } catch (Exception $e) { + $entity = null; } - } - - return $valid; - } - - - // wrappers for Portabilis_*Utils* + return $entity; + } - // DEPRECADO - // #TODO nas classes filhas, migrar chamadas de fetchPreparedQuery para usar novo padrao com array de options - protected function fetchPreparedQuery($sql, $params = array(), $hideExceptions = true, $returnOnly = '') { - $options = array('params' => $params, - 'show_errors' => ! $hideExceptions, - 'return_only' => $returnOnly, - 'messenger' => $this->messenger); - - return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - } - - protected function getDataMapperFor($packageName, $modelName){ - return Portabilis_DataMapper_Utils::getDataMapperFor($packageName, $modelName); - } + protected function createEntityOf($dataMapper, $data = []) + { + return $dataMapper->createNewEntityInstance($data); + } - protected function getEntityOf($dataMapper, $id) { - return $dataMapper->find($id); - } + protected function getOrCreateEntityOf($dataMapper, $id) + { + $entity = $this->tryGetEntityOf($dataMapper, $id); - protected function tryGetEntityOf($dataMapper, $id) { - try { - $entity = $this->getEntityOf($dataMapper, $id); - } - catch(Exception $e) { - $entity = null; + return (is_null($entity) ? $this->createEntityOf($dataMapper) : $entity); } - return $entity; - } - - protected function createEntityOf($dataMapper, $data = array()) { - return $dataMapper->createNewEntityInstance($data); - } + protected function deleteEntityOf($dataMapper, $id) + { + $entity = $this->tryGetEntityOf($dataMapper, $id); - protected function getOrCreateEntityOf($dataMapper, $id) { - $entity = $this->tryGetEntityOf($dataMapper, $id); - return (is_null($entity) ? $this->createEntityOf($dataMapper) : $entity); - } + return (is_null($entity) ? true : $dataMapper->delete($entity)); + } - protected function deleteEntityOf($dataMapper, $id) { - $entity = $this->tryGetEntityOf($dataMapper, $id); - return (is_null($entity) ? true : $dataMapper->delete($entity)); - } + protected function saveEntity($dataMapper, $entity) + { + if ($entity->isValid()) { + $dataMapper->save($entity); + } else { + $errors = $entity->getErrors(); + $msgs = []; - protected function saveEntity($dataMapper, $entity) { - if ($entity->isValid()) - $dataMapper->save($entity); + foreach ($errors as $attr => $msg) { + if (!is_null($msg)) { + $msgs[] = "$attr => $msg"; + } + } - else { - $errors = $entity->getErrors(); - $msgs = array(); + $msg = 'Erro ao salvar o recurso ' . $dataMapper->resourceName() . ': ' . join(', ', $msgs); - foreach ($errors as $attr => $msg) { - if (! is_null($msg)) - $msgs[] = "$attr => $msg"; - } + $this->messenger->append($msg, 'error', true); + } + } - //$msgs transporte_aluno - $msg = 'Erro ao salvar o recurso ' . $dataMapper->resourceName() . ': ' . join(', ', $msgs); - $this->messenger->append($msg, 'error', true); + protected static function mergeOptions($options, $defaultOptions) + { + return Portabilis_Array_Utils::merge($options, $defaultOptions); } - } - protected static function mergeOptions($options, $defaultOptions) { - return Portabilis_Array_Utils::merge($options, $defaultOptions); - } + protected function toUtf8($str, $options = []) + { + return Portabilis_String_Utils::toUtf8($str, $options); + } - protected function toUtf8($str, $options = array()) { - return Portabilis_String_Utils::toUtf8($str, $options); - } + protected function toLatin1($str, $options = []) + { + return Portabilis_String_Utils::toLatin1($str, $options); + } - protected function toLatin1($str, $options = array()) { - return Portabilis_String_Utils::toLatin1($str, $options); - } + protected function safeString($str, $transform = true) + { + return $this->toUtf8($str, ['transform' => $transform]); + } - // DEPRECADO #TODO nas classe filhas migrar de safeString => toUtf8 - protected function safeString($str, $transform = true) { - return $this->toUtf8($str, array('transform' => $transform)); - } + protected function safeStringForDb($str) + { + return $this->toLatin1($str); + } - // DEPRECADO #TODO nas classe filhas migrar de safeStringForDb => toLatin1 - protected function safeStringForDb($str) { - return $this->toLatin1($str); - } + protected function defaultSearchOptions() + { + $resourceName = Portabilis_String_Utils::underscore($this->getDispatcher()->getActionName()); + + return [ + 'namespace' => 'pmieducar', + 'table' => $resourceName, + 'idAttr' => "cod_$resourceName", + 'labelAttr' => 'nome', + 'selectFields' => [], + 'sqlParams' => [] + ]; + } + protected function searchOptions() + { + return []; + } - // search + protected function sqlsForNumericSearch() + { + $searchOptions = $this->mergeOptions($this->searchOptions(), $this->defaultSearchOptions()); - protected function defaultSearchOptions() { - $resourceName = Portabilis_String_Utils::underscore($this->getDispatcher()->getActionName()); + $namespace = $searchOptions['namespace']; + $table = $searchOptions['table']; + $idAttr = $searchOptions['idAttr']; + $labelAttr = $searchOptions['labelAttr']; - return array('namespace' => 'pmieducar', - 'table' => $resourceName, - 'idAttr' => "cod_$resourceName", - 'labelAttr' => 'nome', - 'selectFields' => array(), - 'sqlParams' => array()); - } + $searchOptions['selectFields'][] = "$idAttr as id, $labelAttr as name"; + $selectFields = join(', ', $searchOptions['selectFields']); - // overwrite in subclass to chande search options - protected function searchOptions() { - return array(); - } + return "select distinct $selectFields from $namespace.$table where $idAttr::varchar like $1||'%' order by $idAttr limit 15"; + } - protected function sqlsForNumericSearch() { - $searchOptions = $this->mergeOptions($this->searchOptions(), $this->defaultSearchOptions()); + protected function sqlsForStringSearch() + { + $searchOptions = $this->mergeOptions($this->searchOptions(), $this->defaultSearchOptions()); - $namespace = $searchOptions['namespace']; - $table = $searchOptions['table']; - $idAttr = $searchOptions['idAttr']; - $labelAttr = $searchOptions['labelAttr']; + $namespace = $searchOptions['namespace']; + $table = $searchOptions['table']; + $idAttr = $searchOptions['idAttr']; + $labelAttr = $searchOptions['labelAttr']; - $searchOptions['selectFields'][] = "$idAttr as id, $labelAttr as name"; - $selectFields = join(', ', $searchOptions['selectFields']); + $searchOptions['selectFields'][] = "$idAttr as id, $labelAttr as name"; + $selectFields = join(', ', $searchOptions['selectFields']); - return "select distinct $selectFields from $namespace.$table - where $idAttr::varchar like $1||'%' order by $idAttr limit 15"; - } + return "select distinct $selectFields from $namespace.$table where lower($labelAttr) like '%'||lower($1)||'%' order by $labelAttr limit 15"; + } + protected function sqlParams($query) + { + $searchOptions = $this->mergeOptions($this->searchOptions(), $this->defaultSearchOptions()); + $params = [$query]; - protected function sqlsForStringSearch() { - $searchOptions = $this->mergeOptions($this->searchOptions(), $this->defaultSearchOptions()); + foreach ($searchOptions['sqlParams'] as $param) { + $params[] = $param; + } - $namespace = $searchOptions['namespace']; - $table = $searchOptions['table']; - $idAttr = $searchOptions['idAttr']; - $labelAttr = $searchOptions['labelAttr']; + return $params; + } - $searchOptions['selectFields'][] = "$idAttr as id, $labelAttr as name"; - $selectFields = join(', ', $searchOptions['selectFields']); + protected function loadResourcesBySearchQuery($query) + { + $results = []; + $numericQuery = preg_replace('/[^0-9]/', '', $query); - return "select distinct $selectFields from $namespace.$table - where lower($labelAttr) like '%'||lower($1)||'%' order by $labelAttr limit 15"; - } + if (!empty($numericQuery)) { + $sqls = $this->sqlsForNumericSearch(); + $params = $this->sqlParams($numericQuery); + } else { + $query = Portabilis_String_Utils::toLatin1($query, ['escape' => false]); - protected function sqlParams($query) { - $searchOptions = $this->mergeOptions($this->searchOptions(), $this->defaultSearchOptions()); - $params = array($query); + $sqls = $this->sqlsForStringSearch(); + $params = $this->sqlParams($query); + } - foreach($searchOptions['sqlParams'] as $param) - $params[] = $param; + if (!is_array($sqls)) { + $sqls = [$sqls]; + } - return $params; - } + foreach ($sqls as $sql) { + $_results = $this->fetchPreparedQuery($sql, $params, false); - protected function loadResourcesBySearchQuery($query) { - $results = array(); - $numericQuery = preg_replace("/[^0-9]/", "", $query); + foreach ($_results as $result) { + if (!isset($results[$result['id']])) { + $results[$result['id']] = $this->formatResourceValue($result); + } + } + } - if (! empty($numericQuery)) { - $sqls = $this->sqlsForNumericSearch(); - $params = $this->sqlParams($numericQuery); + return $results; } - else { - // convertido query para latin1, para que pesquisas com acentuação funcionem. - $query = Portabilis_String_Utils::toLatin1($query, array('escape' => false)); - - $sqls = $this->sqlsForStringSearch(); - $params = $this->sqlParams($query); + protected function formatResourceValue($resource) + { + return $resource['id'] . ' - ' . $this->toUtf8($resource['name'], ['transform' => true]); } - if (! is_array($sqls)) - $sqls = array($sqls); + protected function search() + { + if ($this->canSearch()) { + $resources = $this->loadResourcesBySearchQuery($this->getRequest()->query); + } - foreach($sqls as $sql) { - $_results = $this->fetchPreparedQuery($sql, $params, false); + if (empty($resources)) { + $resources = ['' => 'Sem resultados.']; + } - foreach($_results as $result) { - if (! isset($results[$result['id']])) - $results[$result['id']] = $this->formatResourceValue($result); - } + return ['result' => $resources]; } - - return $results; - } - - // formats the value of each resource, that will be returned in api as a label. - - protected function formatResourceValue($resource) { - return $resource['id'] . ' - ' . $this->toUtf8($resource['name'], array('transform' => true)); - } - - - // default api responders - - protected function search() { - if ($this->canSearch()) - $resources = $this->loadResourcesBySearchQuery($this->getRequest()->query); - - if (empty($resources)) - $resources = array('' => 'Sem resultados.'); - - return array('result' => $resources); - } } diff --git a/ieducar/lib/Portabilis/Controller/ErrorCoreController.php b/ieducar/lib/Portabilis/Controller/ErrorCoreController.php index 3410b40abf..067b331c2b 100644 --- a/ieducar/lib/Portabilis/Controller/ErrorCoreController.php +++ b/ieducar/lib/Portabilis/Controller/ErrorCoreController.php @@ -1,36 +1,7 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @subpackage lib - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ +ini_set('display_errors', 1); require_once 'Core/View.php'; require_once 'Core/Controller/Page/ViewController.php'; @@ -38,52 +9,54 @@ class Portabilis_Controller_ErrorCoreController extends Core_Controller_Page_ViewController { - protected $_titulo = 'Error'; + protected $_titulo = 'Error'; - public function __construct() { - parent::__construct(); - $this->loadAssets(); - } + public function __construct() + { + parent::__construct(); - /* overwrite Core/Controller/Page/Abstract.php para renderizar html - sem necessidade de usuário estar logado */ - public function generate(CoreExt_Controller_Page_Interface $instance) - { - $this->setHeader(); + $this->loadAssets(); + } - $viewBase = new Core_View($instance); - $viewBase->titulo = $this->_titulo; - $viewBase->addForm($instance); + public function generate(CoreExt_Controller_Page_Interface $instance) + { + $this->setHeader(); - $html = $viewBase->MakeHeadHtml(); + $viewBase = new Core_View($instance); + $viewBase->titulo = $this->_titulo; + $viewBase->addForm($instance); - foreach ($viewBase->clsForm as $form) { - $html .= $form->Gerar(); - } + $html = $viewBase->MakeHeadHtml(); - $html .= $form->getAppendedOutput(); - $html .= $viewBase->MakeFootHtml(); + foreach ($viewBase->clsForm as $form) { + $html .= $form->Gerar(); + } - echo $html; - } + $html .= $form->getAppendedOutput(); + $html .= $viewBase->MakeFootHtml(); - protected function loadAssets() { - $styles = array( - 'styles/reset.css', - 'styles/portabilis.css', - 'styles/min-portabilis.css', - '/modules/Error/Assets/Stylesheets/Error.css' - ); + echo $html; + } - Portabilis_View_Helper_Application::loadStylesheet($this, $styles); - } + protected function loadAssets() + { + $styles = [ + 'styles/reset.css', + 'styles/portabilis.css', + 'styles/min-portabilis.css', + '/modules/Error/Assets/Stylesheets/Error.css' + ]; + Portabilis_View_Helper_Application::loadStylesheet($this, $styles); + } - protected function setHeader() { - die('setHeader must be overwritten!'); - } + protected function setHeader() + { + die('setHeader must be overwritten!'); + } - public function Gerar() { - die('Gerar must be overwritten!'); - } + public function Gerar() + { + die('Gerar must be overwritten!'); + } } diff --git a/ieducar/lib/Portabilis/Controller/Page/EditController.php b/ieducar/lib/Portabilis/Controller/Page/EditController.php index dc94aaee30..f4f88edcbb 100644 --- a/ieducar/lib/Portabilis/Controller/Page/EditController.php +++ b/ieducar/lib/Portabilis/Controller/Page/EditController.php @@ -1,209 +1,162 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @subpackage lib - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ - require_once 'Core/Controller/Page/EditController.php'; - require_once 'lib/Portabilis/Messenger.php'; require_once 'lib/Portabilis/Validator.php'; require_once 'lib/Portabilis/Array/Utils.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/DataMapper/Utils.php'; - require_once 'lib/Portabilis/View/Helper/Application.php'; -// Resource controller class Portabilis_Controller_Page_EditController extends Core_Controller_Page_EditController { + protected $_dataMapper = null; - protected $_dataMapper = null; - - # vars that must be overwritten in subclasses - # protected $_processoAp = 0; - # protected $_nivelAcessoOption = App_Model_NivelAcesso::SOMENTE_ESCOLA; - - # vars that can be overwritten - # protected $_dataMapper = 'Avaliacao_Model_NotaComponenteDataMapper'; - # protected $_saveOption = FALSE; - # protected $_deleteOption = FALSE; - # protected $_titulo = 'Cadastro de aluno'; - - protected $_nivelAcessoInsuficiente = "/module/Error/unauthorized"; - - - protected $_titulo = ''; - protected $backwardCompatibility = false; - - public function __construct(){ - parent::__construct(); - $this->loadAssets(); - } - - // methods that can be overwritten - - protected function canSave() - { - return true; - } - - - // methods that must be overwritten - - function Gerar() - { - throw new Exception("The method 'Gerar' must be overwritten!"); - } - - - protected function save() - { - throw new Exception("The method 'save' must be overwritten!"); - } + protected $_nivelAcessoInsuficiente = '/module/Error/unauthorized'; + protected $_titulo = ''; - // methods that cannot be overwritten + protected $backwardCompatibility = false; - protected function _save() - { - $result = false; + public function __construct() + { + parent::__construct(); + $this->loadAssets(); + } - // try set or load entity before validation or save - if (! $this->_initNovo()) - $this->_initEditar(); + protected function canSave() + { + return true; + } - if (! $this->messenger()->hasMsgWithType('error') && $this->canSave()) { - try { - $result = $this->save(); + public function Gerar() + { + throw new Exception('The method \'Gerar\' must be overwritten!'); + } - if (is_null($result)) - $result = ! $this->messenger()->hasMsgWithType('error'); - elseif(! is_bool($result)) - throw new Exception("Invalid value returned from '_save' method: '$result', please return null, true or false!"); - } - catch (Exception $e) { - $this->messenger()->append('Erro ao gravar alterações, por favor, tente novamente.', 'error'); - error_log("Erro ao gravar alteracoes: " . $e->getMessage()); + protected function save() + { + throw new Exception('The method \'save\' must be overwritten!'); + } + protected function _save() + { $result = false; - } - $result = $result && ! $this->messenger()->hasMsgWithType('error'); + if (!$this->_initNovo()) { + $this->_initEditar(); + } - if ($result) - $this->messenger()->append('Alterações gravadas com sucesso.', 'success', false, 'success'); - } + if (!$this->messenger()->hasMsgWithType('error') && $this->canSave()) { + try { + $result = $this->save(); - return $result; - } + if (is_null($result)) { + $result = !$this->messenger()->hasMsgWithType('error'); + } elseif (!is_bool($result)) { + throw new Exception("Invalid value returned from '_save' method: '$result', please return null, true or false!"); + } + } catch (Exception $e) { + $this->messenger()->append('Erro ao gravar alterações, por favor, tente novamente.', 'error'); + error_log('Erro ao gravar alteracoes: ' . $e->getMessage()); + $result = false; + } - protected function flashMessage() - { - if (! $this->hasErrors()) - return $this->messenger()->toHtml(); + $result = $result && !$this->messenger()->hasMsgWithType('error'); - return ''; - } + if ($result) { + $this->messenger()->append('Alterações gravadas com sucesso.', 'success', false, 'success'); + } + } - - // helpers - - protected function validator() { - if (! isset($this->_validator)) { - // FIXME #parameters - $messenger = null; - $this->_validator = new Portabilis_Validator($messenger); + return $result; } - return $this->_validator; - } - - - protected function messenger() { - if (! isset($this->_messenger)) - $this->_messenger = new Portabilis_Messenger(); + protected function flashMessage() + { + if (!$this->hasErrors()) { + return $this->messenger()->toHtml(); + } - return $this->_messenger; - } + return ''; + } - protected function loadResourceAssets($dispatcher){ - $rootPath = $_SERVER['DOCUMENT_ROOT']; - $controllerName = ucwords($dispatcher->getControllerName()); - $actionName = ucwords($dispatcher->getActionName()); + protected function validator() + { + if (!isset($this->_validator)) { + // FIXME #parameters + $messenger = null; + $this->_validator = new Portabilis_Validator($messenger); + } - $style = "/modules/$controllerName/Assets/Stylesheets/$actionName.css"; - $script = "/modules/$controllerName/Assets/Javascripts/$actionName.js"; + return $this->_validator; + } - if (file_exists($rootPath . $style)) - Portabilis_View_Helper_Application::loadStylesheet($this, $style); + protected function messenger() + { + if (!isset($this->_messenger)) { + $this->_messenger = new Portabilis_Messenger(); + } - if (file_exists($rootPath . $script)) - Portabilis_View_Helper_Application::loadJavascript($this, $script); - } + return $this->_messenger; + } - protected function loadAssets(){ - Portabilis_View_Helper_Application::loadJQueryFormLib($this); + protected function loadResourceAssets($dispatcher) + { + $rootPath = $_SERVER['DOCUMENT_ROOT']; + $controllerName = ucwords($dispatcher->getControllerName()); + $actionName = ucwords($dispatcher->getActionName()); - $styles = array('/modules/Portabilis/Assets/Stylesheets/Frontend.css', - '/modules/Portabilis/Assets/Stylesheets/Frontend/Resource.css', - 'styles/localizacaoSistema.css'); - Portabilis_View_Helper_Application::loadStylesheet($this, $styles); + $style = "/modules/$controllerName/Assets/Stylesheets/$actionName.css"; + $script = "/modules/$controllerName/Assets/Javascripts/$actionName.js"; + if (file_exists($rootPath . $style)) { + Portabilis_View_Helper_Application::loadStylesheet($this, $style); + } - $scripts = array('/modules/Portabilis/Assets/Javascripts/ClientApi.js', - '/modules/Portabilis/Assets/Javascripts/Validator.js', - '/modules/Portabilis/Assets/Javascripts/Utils.js'); + if (file_exists($rootPath . $script)) { + Portabilis_View_Helper_Application::loadJavascript($this, $script); + } + } - if (! $this->backwardCompatibility) - $scripts[] = '/modules/Portabilis/Assets/Javascripts/Frontend/Resource.js'; + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadJQueryFormLib($this); - Portabilis_View_Helper_Application::loadJavascript($this, $scripts); - } + $styles = [ + '/modules/Portabilis/Assets/Stylesheets/Frontend.css', + '/modules/Portabilis/Assets/Stylesheets/Frontend/Resource.css', + 'styles/localizacaoSistema.css' + ]; + Portabilis_View_Helper_Application::loadStylesheet($this, $styles); - // wrappers for Portabilis_*Utils* + $scripts = [ + '/modules/Portabilis/Assets/Javascripts/ClientApi.js', + '/modules/Portabilis/Assets/Javascripts/Validator.js', + '/modules/Portabilis/Assets/Javascripts/Utils.js' + ]; - protected static function mergeOptions($options, $defaultOptions) { - return Portabilis_Array_Utils::merge($options, $defaultOptions); - } + if (!$this->backwardCompatibility) { + $scripts[] = '/modules/Portabilis/Assets/Javascripts/Frontend/Resource.js'; + } + Portabilis_View_Helper_Application::loadJavascript($this, $scripts); + } - protected function fetchPreparedQuery($sql, $options = array()) { - return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - } + protected static function mergeOptions($options, $defaultOptions) + { + return Portabilis_Array_Utils::merge($options, $defaultOptions); + } + protected function fetchPreparedQuery($sql, $options = []) + { + return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + } - protected function getDataMapperFor($packageName, $modelName){ - return Portabilis_DataMapper_Utils::getDataMapperFor($packageName, $modelName); - } + protected function getDataMapperFor($packageName, $modelName) + { + return Portabilis_DataMapper_Utils::getDataMapperFor($packageName, $modelName); + } } diff --git a/ieducar/lib/Portabilis/Controller/Page/ListController.php b/ieducar/lib/Portabilis/Controller/Page/ListController.php index 6ab2f1c715..6b0ccff13b 100644 --- a/ieducar/lib/Portabilis/Controller/Page/ListController.php +++ b/ieducar/lib/Portabilis/Controller/Page/ListController.php @@ -1,86 +1,61 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Avaliacao - * @subpackage Modules - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ - require_once 'Core/Controller/Page/ListController.php'; require_once 'lib/Portabilis/View/Helper/Application.php'; -require_once "lib/Portabilis/View/Helper/Inputs.php"; +require_once 'lib/Portabilis/View/Helper/Inputs.php'; -// Process controller class Portabilis_Controller_Page_ListController extends Core_Controller_Page_ListController { - - protected $backwardCompatibility = false; - - public function __construct() { - $this->rodape = ""; - $this->largura = '100%'; - - $this->loadAssets(); - parent::__construct(); - } - - protected function loadResourceAssets($dispatcher){ - $rootPath = $_SERVER['DOCUMENT_ROOT']; - $controllerName = ucwords($dispatcher->getControllerName()); - $actionName = ucwords($dispatcher->getActionName()); - - $style = "/modules/$controllerName/Assets/Stylesheets/$actionName.css"; - $script = "/modules/$controllerName/Assets/Javascripts/$actionName.js"; - - if (file_exists($rootPath . $style)) - Portabilis_View_Helper_Application::loadStylesheet($this, $style); - - if (file_exists($rootPath . $script)) - Portabilis_View_Helper_Application::loadJavascript($this, $script); - } - - protected function loadAssets(){ - Portabilis_View_Helper_Application::loadJQueryFormLib($this); - - $styles = array('/modules/Portabilis/Assets/Stylesheets/Frontend.css', - '/modules/Portabilis/Assets/Stylesheets/Frontend/Process.css'); - Portabilis_View_Helper_Application::loadStylesheet($this, $styles); - - $scripts = array( - '/modules/Portabilis/Assets/Javascripts/ClientApi.js', - '/modules/Portabilis/Assets/Javascripts/Validator.js', - '/modules/Portabilis/Assets/Javascripts/Utils.js' - ); - - if (! $this->backwardCompatibility) - $scripts[] = '/modules/Portabilis/Assets/Javascripts/Frontend/Process.js'; - - Portabilis_View_Helper_Application::loadJavascript($this, $scripts); - } -} \ No newline at end of file + protected $backwardCompatibility = false; + + public function __construct() + { + $this->rodape = ''; + $this->largura = '100%'; + + $this->loadAssets(); + parent::__construct(); + } + + protected function loadResourceAssets($dispatcher) + { + $rootPath = $_SERVER['DOCUMENT_ROOT']; + $controllerName = ucwords($dispatcher->getControllerName()); + $actionName = ucwords($dispatcher->getActionName()); + + $style = "/modules/$controllerName/Assets/Stylesheets/$actionName.css"; + $script = "/modules/$controllerName/Assets/Javascripts/$actionName.js"; + + if (file_exists($rootPath . $style)) { + Portabilis_View_Helper_Application::loadStylesheet($this, $style); + } + + if (file_exists($rootPath . $script)) { + Portabilis_View_Helper_Application::loadJavascript($this, $script); + } + } + + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadJQueryFormLib($this); + + $styles = [ + '/modules/Portabilis/Assets/Stylesheets/Frontend.css', + '/modules/Portabilis/Assets/Stylesheets/Frontend/Process.css' + ]; + + Portabilis_View_Helper_Application::loadStylesheet($this, $styles); + + $scripts = [ + '/modules/Portabilis/Assets/Javascripts/ClientApi.js', + '/modules/Portabilis/Assets/Javascripts/Validator.js', + '/modules/Portabilis/Assets/Javascripts/Utils.js' + ]; + + if (!$this->backwardCompatibility) { + $scripts[] = '/modules/Portabilis/Assets/Javascripts/Frontend/Process.js'; + } + + Portabilis_View_Helper_Application::loadJavascript($this, $scripts); + } +} diff --git a/ieducar/lib/Portabilis/Controller/ReportCoreController.php b/ieducar/lib/Portabilis/Controller/ReportCoreController.php index c2b77540c1..2ac92e42e9 100644 --- a/ieducar/lib/Portabilis/Controller/ReportCoreController.php +++ b/ieducar/lib/Portabilis/Controller/ReportCoreController.php @@ -45,7 +45,6 @@ public function __construct() $this->validationErrors = []; - // clsCadastro settings $this->acao_executa_submit = false; $this->acao_enviar = 'printReport()'; @@ -137,8 +136,10 @@ public function renderReport() } $this->headers($result); + ob_clean(); flush(); + echo $result; } catch (Exception $e) { if ($GLOBALS['coreExt']['Config']->modules->error->track) { diff --git a/ieducar/lib/Portabilis/Currency/Utils.php b/ieducar/lib/Portabilis/Currency/Utils.php index 5bb2730e92..737130ceb1 100644 --- a/ieducar/lib/Portabilis/Currency/Utils.php +++ b/ieducar/lib/Portabilis/Currency/Utils.php @@ -1,54 +1,23 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version $Id$ - */ +class Portabilis_Currency_Utils +{ + /** + * Converte um valor numérico de moeda brasileira (ex: 2,32) para + * estrangeira (2.32). + */ + public static function moedaBrToUs($valor) + { + return str_replace(',', '.', (str_replace('.', '', $valor))); + } -/** - * Portabilis_Currency_Utils class. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version @@package_version@@ - */ -class Portabilis_Currency_Utils { - - //converte um valor numérico de moeda brasileira (ex: 2,32) para estrangeira (2.32) - public static function moedaBrToUs($valor) { - return str_replace(',', '.', (str_replace('.', '', $valor))); - } - - //converte um valor numérico de moeda estrangeira (ex: 2.32) para brasileira (2,32) - public static function moedaUsToBr($valor){ - return str_replace('.', ',', $valor); - } - + /** + * Converte um valor numérico de moeda estrangeira (ex: 2.32) para + * brasileira (2,32). + */ + public static function moedaUsToBr($valor) + { + return str_replace('.', ',', $valor); + } } diff --git a/ieducar/lib/Portabilis/DataMapper/Utils.php b/ieducar/lib/Portabilis/DataMapper/Utils.php index 8965c72a4e..d547c84e9b 100644 --- a/ieducar/lib/Portabilis/DataMapper/Utils.php +++ b/ieducar/lib/Portabilis/DataMapper/Utils.php @@ -1,67 +1,18 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * Portabilis_DataMapper_Utils class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_DataMapper_Utils { - - /* - this method returns a data mapper loaded by module_package and model_name, eg: - - $resourceDataMapper = $this->getDataMapperFor('module_package', 'model_name'); - $columns = array('col_1', 'col_2'); - $where = array('col_3' => 'val_1', 'ativo' => '1'); - $orderBy = array('col_4' => 'ASC'); - - $resources = $resourceDataMapper->findAll($columns, $where, $orderBy, $addColumnIdIfNotSet = false); - - */ - public function getDataMapperFor($packageName, $modelName){ - $dataMapperClassName = ucfirst($packageName) . "_Model_" . ucfirst($modelName) . "DataMapper"; - $classPath = str_replace('_', '/', $dataMapperClassName) . '.php'; - - // don't raise any error if the file to be included not exists or it already included. - include_once $classPath; - - if (! class_exists($dataMapperClassName)) - throw new CoreExt_Exception("Class '$dataMapperClassName' not found in path $classPath."); - - return new $dataMapperClassName(); - } - -} \ No newline at end of file +class Portabilis_DataMapper_Utils +{ + public function getDataMapperFor($packageName, $modelName) + { + $dataMapperClassName = ucfirst($packageName) . '_Model_' . ucfirst($modelName) . 'DataMapper'; + $classPath = str_replace('_', '/', $dataMapperClassName) . '.php'; + + include_once $classPath; + + if (!class_exists($dataMapperClassName)) { + throw new CoreExt_Exception("Class '$dataMapperClassName' not found in path $classPath."); + } + + return new $dataMapperClassName(); + } +} diff --git a/ieducar/lib/Portabilis/Date/Utils.php b/ieducar/lib/Portabilis/Date/Utils.php index 660b7176e1..f0ec9aa296 100644 --- a/ieducar/lib/Portabilis/Date/Utils.php +++ b/ieducar/lib/Portabilis/Date/Utils.php @@ -1,141 +1,131 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis_Date - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * Portabilis_Date_Utils class. - * - * Possui métodos - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package App_Date - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ - class Portabilis_Date_Utils { - /** - * Recebe uma data no formato dd/mm/yyyy e retorna no formato postgres yyyy-mm-dd. - * @param string $date - */ - public static function brToPgSQL($date) { - if (! $date) - return $date; - - // #TODO usar classe nativa datetime http://www.phptherightway.com/#date_and_time ? - list($dia, $mes, $ano) = explode("/", $date); - return "$ano-$mes-$dia"; - } - - /** - * Recebe uma data no formato dd/mm e retorna no formato postgres yyyy-mm-dd. - * @param string $date - */ - public static function brToPgSQL_ddmm($date) { - if (! $date) - return $date; - - // #TODO usar classe nativa datetime http://www.phptherightway.com/#date_and_time ? - list($dia, $mes) = explode("/", $date); - $ano = '1900'; - return "$ano-$mes-$dia"; - } - - /** - * Recebe uma data no formato postgres yyyy-mm-dd hh:mm:ss.uuuu e retorna no formato br dd/mm/yyyy hh:mm:ss. - * @param string $timestamp - */ - public static function pgSQLToBr($timestamp) { - $pgFormat = 'Y-m-d'; - $brFormat = 'd/m/Y'; - - $hasTime = strpos($timestamp, ':') > -1; - - if ($hasTime) { - $pgFormat .= ' H:i:s'; - $brFormat .= ' H:i:s'; - - $hasMicroseconds = strpos($timestamp, '.') > -1; - - if ($hasMicroseconds) - $pgFormat .= '.u'; + /** + * Recebe uma data no formato dd/mm/yyyy e retorna no formato postgres + * yyyy-mm-dd. + * + * @param string $date + * + * @return string + */ + public static function brToPgSQL($date) + { + if (!$date) { + return $date; + } + + list($dia, $mes, $ano) = explode('/', $date); + + return "$ano-$mes-$dia"; + } + + /** + * Recebe uma data no formato dd/mm e retorna no formato postgres + * yyyy-mm-dd. + * + * @param string $date + * + * @return string + */ + public static function brToPgSQL_ddmm($date) + { + if (!$date) { + return $date; + } + + list($dia, $mes) = explode('/', $date); + + $ano = '1900'; + + return "$ano-$mes-$dia"; } - $d = DateTime::createFromFormat($pgFormat, $timestamp); - - return ($d ? $d->format($brFormat) : null); - } - - /** - * Recebe uma data no formato postgres yyyy-mm-dd hh:mm:ss.uuuu e retorna no formato br dd/mm. - * @param string $timestamp - */ - public static function pgSQLToBr_ddmm($timestamp) { - $pgFormat = 'Y-m-d'; - $brFormat = 'd/m'; - - $d = DateTime::createFromFormat($pgFormat, $timestamp); - - return ($d ? $d->format($brFormat) : null); - } - public static function validaData($date){ - $date_arr = explode('/', $date); - if(count($date_arr) == 3){ - if(checkdate($date_arr[1], $date_arr[0], $date_arr[2])){ - return true; - }else{ + /** + * Recebe uma data no formato postgres yyyy-mm-dd hh:mm:ss.uuuu e retorna + * no formato br dd/mm/yyyy hh:mm:ss. + * + * @param string $timestamp + * + * @return null|string + */ + public static function pgSQLToBr($timestamp) + { + $pgFormat = 'Y-m-d'; + $brFormat = 'd/m/Y'; + + $hasTime = strpos($timestamp, ':') > -1; + + if ($hasTime) { + $pgFormat .= ' H:i:s'; + $brFormat .= ' H:i:s'; + + $hasMicroseconds = strpos($timestamp, '.') > -1; + + if ($hasMicroseconds) { + $pgFormat .= '.u'; + } + } + + $d = DateTime::createFromFormat($pgFormat, $timestamp); + + return ($d ? $d->format($brFormat) : null); + } + + /** + * Recebe uma data no formato postgres yyyy-mm-dd hh:mm:ss.uuuu e retorna + * no formato br dd/mm. + * + * @param string $timestamp + * + * @return null|string + */ + public static function pgSQLToBr_ddmm($timestamp) + { + $pgFormat = 'Y-m-d'; + $brFormat = 'd/m'; + + $d = DateTime::createFromFormat($pgFormat, $timestamp); + + return ($d ? $d->format($brFormat) : null); + } + + public static function validaData($date) + { + $date_arr = explode('/', $date); + + if (count($date_arr) == 3) { + if (checkdate($date_arr[1], $date_arr[0], $date_arr[2])) { + return true; + } else { + return false; + } + } else { return false; } - }else{ - return false; } - } - - /** - * Recebe uma data no formato yyyy-mm-dd e verifica se é uma data válida considerando o ano bissexto. - * @param string $timestamp - */ - public static function checkDateBissexto($data) { - $data = date_parse_from_format("Y-m-d", $data); - $day = (int)$data["day"]; - $month = (int)$data["month"]; - $year = (int)$data["year"]; - - return ($day == 29 && !checkdate($month, $day, $year)); - } - - public static function isDateValid($date, $format = 'Y-m-d') - { - return (boolean) DateTime::createFromFormat($format, $date); - } + /** + * Recebe uma data no formato yyyy-mm-dd e verifica se é uma data válida + * considerando o ano bissexto. + * + * @param string $data + * + * @return bool + */ + public static function checkDateBissexto($data) + { + $data = date_parse_from_format('Y-m-d', $data); + $day = (int) $data['day']; + $month = (int) $data['month']; + $year = (int) $data['year']; + + return ($day == 29 && !checkdate($month, $day, $year)); + } + + public static function isDateValid($date, $format = 'Y-m-d') + { + return (boolean) DateTime::createFromFormat($format, $date); + } } diff --git a/ieducar/lib/Portabilis/Mailer.php b/ieducar/lib/Portabilis/Mailer.php index 3a0c1457ca..4efea9b203 100644 --- a/ieducar/lib/Portabilis/Mailer.php +++ b/ieducar/lib/Portabilis/Mailer.php @@ -2,19 +2,18 @@ require_once 'vendor/autoload.php'; -class Portabilis_Mailer { - +class Portabilis_Mailer +{ public $config = []; protected $transport; + protected $mailer; + protected $logger; public function __construct() { - /* Configurações podem ser alteradas em tempo de execução, ex: - $mailerInstance->configs->smtp->username = 'new_username'; */ - $this->config = $GLOBALS['coreExt']['Config']->app->mailer; } @@ -40,7 +39,7 @@ public function sendMail($to, $subject, $message, $options = []) $this->mailer = new Swift_Mailer($this->transport); - if ((bool)$this->config->debug || (bool)$options['debug']) { + if ((bool) $this->config->debug || (bool) $options['debug']) { $this->logger = new Swift_Plugins_Loggers_ArrayLogger(); $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger)); } @@ -77,7 +76,7 @@ public function sendMail($to, $subject, $message, $options = []) public function debug() { - if ((bool)$this->config->debug || (bool)$options['debug']) { + if ((bool) $this->config->debug || (bool) $options['debug']) { return $this->logger->dump(); } } diff --git a/ieducar/lib/Portabilis/Messenger.php b/ieducar/lib/Portabilis/Messenger.php index 4b67902341..60b51d2d95 100644 --- a/ieducar/lib/Portabilis/Messenger.php +++ b/ieducar/lib/Portabilis/Messenger.php @@ -1,102 +1,67 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - - -/** - * Portabilis_Messenger class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ - -class Portabilis_Messenger { - - public function __construct() { - $this->_msgs = array(); - } - - - public function append($msg, $type="error", $encodeToUtf8 = false, $ignoreIfHasMsgWithType = '') { - if (empty($ignoreIfHasMsgWithType) || ! $this->hasMsgWithType($ignoreIfHasMsgWithType)) { +class Portabilis_Messenger +{ + public function __construct() + { + $this->_msgs = []; + } - if ($encodeToUtf8) - $msg = utf8_encode($msg); + public function append($msg, $type = 'error', $encodeToUtf8 = false, $ignoreIfHasMsgWithType = '') + { + if (empty($ignoreIfHasMsgWithType) || !$this->hasMsgWithType($ignoreIfHasMsgWithType)) { + if ($encodeToUtf8) { + $msg = utf8_encode($msg); + } - $this->_msgs[] = array('msg' => $msg, 'type' => $type); + $this->_msgs[] = ['msg' => $msg, 'type' => $type]; + } } - } + public function hasMsgWithType($type) + { + $hasMsg = false; - public function hasMsgWithType($type) { - $hasMsg = false; + foreach ($this->_msgs as $m) { + if ($m['type'] == $type) { + $hasMsg = true; + break; + } + } - foreach ($this->_msgs as $m){ - if ($m['type'] == $type) { - $hasMsg = true; - break; - } + return $hasMsg; } - return $hasMsg; - } - - - public function toHtml($tag = 'p') { - $msgs = ''; + public function toHtml($tag = 'p') + { + $msgs = ''; - foreach($this->getMsgs() as $m) - $msgs .= "<$tag class='{$m['type']}'>{$m['msg']}"; + foreach ($this->getMsgs() as $m) { + $msgs .= "<$tag class='{$m['type']}'>{$m['msg']}"; + } - return $msgs; - } + return $msgs; + } + public function getMsgs() + { + $msgs = []; - public function getMsgs() { - $msgs = array(); + // expoe explicitamente apenas as chaves 'msg' e 'type', evitando + // exposição indesejada de chaves adicionadas futuramente ao array + // $this->_msgs - // expoe explicitamente apenas as chaves 'msg' e 'type', evitando exposição - // indesejada de chaves adicionadas futuramente ao array $this->_msgs - foreach($this->_msgs as $m) - $msgs[] = array('msg' => $m['msg'], 'type' => $m['type']); + foreach ($this->_msgs as $m) { + $msgs[] = ['msg' => $m['msg'], 'type' => $m['type']]; + } - return $msgs; - } + return $msgs; + } - // merge messages from another messenger with it self - public function merge($anotherMessenger) { - foreach($anotherMessenger->getMsgs() as $msg) { - $this->append($msg['msg'], $msg['type']); + public function merge($anotherMessenger) + { + foreach ($anotherMessenger->getMsgs() as $msg) { + $this->append($msg['msg'], $msg['type']); + } } - } -} \ No newline at end of file +} diff --git a/ieducar/lib/Portabilis/Object/Utils.php b/ieducar/lib/Portabilis/Object/Utils.php index 44c8e922c8..c5fd3f04e5 100644 --- a/ieducar/lib/Portabilis/Object/Utils.php +++ b/ieducar/lib/Portabilis/Object/Utils.php @@ -1,100 +1,71 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ +class Portabilis_Object_Utils +{ + public static function filterSet($objects, $attrs = []) + { + if (!is_array($objects)) { + $objects = [$objects]; + } -/** - * Portabilis_Object_Utils class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Object_Utils { + $objectsFiltered = []; - public static function filterSet($objects, $attrs = array()){ - if (! is_array($objects)) - $objects = array($objects); + foreach ($objects as $object) { + $objectsFiltered[] = self::filter($object, $attrs); + } - $objectsFiltered = array(); - - foreach($objects as $object) - $objectsFiltered[] = self::filter($object, $attrs); - - return $objectsFiltered; - } - - - /* Retorna um array {key => value, key => value} - de atributos filtrados de um objeto, podendo renomear nome dos attrs, - util para filtrar um objetos a ser retornado por uma api - - $objects - objeto ou array de objetos a ser(em) filtrado(s) - $attrs - atributo ou array de atributos para filtrar objeto, - ex: $attrs = array('cod_escola' => 'id', 'nome') - */ - public static function filter($object, $attrs = array()){ - if (! is_array($attrs)) - $attrs = array($attrs); - - $objectFiltered = array(); - - // apply filter - foreach($attrs as $keyAttr => $valueAtt) { - if (! is_string($keyAttr)) - $keyAttr = $valueAtt; - - $objectFiltered[$valueAtt] = $object->$keyAttr; + return $objectsFiltered; } - return $objectFiltered; - } - - - /* Retorna um array { key => value, key2 => value2 }, filtrados de um array (lista) de objetos, - util para filtar uma lista de objetos a ser usado para criar um input select. - $objects - objeto ou array de objetos a ser(em) filtrado(s) - $keyAttr - nome do atributo respectivo a chave, a filtrar no objeto, - $valueAtt - nome do atributo respectivo ao valor a filtrar no objeto, - */ - public static function asIdValue($objects, $keyAttr, $valueAtt){ - $objectsFiltered = array(); - - if (! is_array($objects)) - $objects = array($objects); - - // apply filter - foreach($objects as $object) - $objectsFiltered[$object->$keyAttr] = $object->$valueAtt; + /** + * Retorna um array {key => value, key => value} de atributos filtrados de + * um objeto, podendo renomear nome dos attrs, util para filtrar um objetos + * a ser retornado por uma api. + * + * $objects - objeto ou array de objetos a ser(em) filtrado(s) + * $attrs - atributo ou array de atributos para filtrar objeto + * + * Ex: $attrs = array('cod_escola' => 'id', 'nome') + */ + public static function filter($object, $attrs = []) + { + if (!is_array($attrs)) { + $attrs = [$attrs]; + } + + $objectFiltered = []; + + foreach ($attrs as $keyAttr => $valueAtt) { + if (!is_string($keyAttr)) { + $keyAttr = $valueAtt; + } + + $objectFiltered[$valueAtt] = $object->$keyAttr; + } + + return $objectFiltered; + } - return $objectsFiltered; - } + /** + * Retorna um array { key => value, key2 => value2 }, filtrados de um array + * (lista) de objetos, util para filtar uma lista de objetos a ser usado + * para criar um input select. + * $objects - objeto ou array de objetos a ser(em) filtrado(s) + * $keyAttr - nome do atributo respectivo a chave, a filtrar no objeto + * $valueAtt - nome do atributo respectivo ao valor a filtrar no objeto + */ + public static function asIdValue($objects, $keyAttr, $valueAtt) + { + $objectsFiltered = []; + + if (!is_array($objects)) { + $objects = [$objects]; + } + + foreach ($objects as $object) { + $objectsFiltered[$object->$keyAttr] = $object->$valueAtt; + } + + return $objectsFiltered; + } } diff --git a/ieducar/lib/Portabilis/Report/ReportFactory.php b/ieducar/lib/Portabilis/Report/ReportFactory.php index 88d77f96c0..fe6bbb8382 100644 --- a/ieducar/lib/Portabilis/Report/ReportFactory.php +++ b/ieducar/lib/Portabilis/Report/ReportFactory.php @@ -55,7 +55,7 @@ abstract public function setSettings($config); * Renderiza o relatório. * * @param Portabilis_Report_ReportCore $report - * @param array $options + * @param array $options * * @return mixed */ diff --git a/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasper.php b/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasper.php index cdd7ba0acb..22cad47f6d 100644 --- a/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasper.php +++ b/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasper.php @@ -58,10 +58,10 @@ public function logoPath() * Renderiza o relatório. * * @param Portabilis_Report_ReportCore $report - * @param array $options + * @param array $options * * @return void - * + * * @throws Exception */ public function dumps($report, $options = []) @@ -99,7 +99,6 @@ public function dumps($report, $options = []) // informar qual tipo de data source será utilizado. if ($report->useJson()) { - $data = $report->getJsonData(); $json = json_encode($data); @@ -113,15 +112,14 @@ public function dumps($report, $options = []) ['pdf'], $report->args, [ - 'driver'=>'json', + 'driver' => 'json', 'json_query' => $report->getJsonQuery(), - 'data_file' => $dataFile + 'data_file' => $dataFile ], false // Não executar em background garante que o erro será retornado )->execute(); unlink($dataFile); - } else { $builder->process( $jasperFile, diff --git a/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasperXML.php b/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasperXML.php index e6b26448cc..b643602e40 100644 --- a/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasperXML.php +++ b/ieducar/lib/Portabilis/Report/ReportFactoryPHPJasperXML.php @@ -69,7 +69,7 @@ public function logoPath() * Renderiza o relatório. * * @param Portabilis_Report_ReportCore $report - * @param array $options + * @param array $options * * @return void * diff --git a/ieducar/lib/Portabilis/Report/ReportFactoryRemote.php b/ieducar/lib/Portabilis/Report/ReportFactoryRemote.php index 1ac99e5204..5733a4a82b 100644 --- a/ieducar/lib/Portabilis/Report/ReportFactoryRemote.php +++ b/ieducar/lib/Portabilis/Report/ReportFactoryRemote.php @@ -25,7 +25,7 @@ public function setSettings($config) * Renderiza o relatório. * * @param Portabilis_Report_ReportCore $report - * @param array $options + * @param array $options * * @return mixed * diff --git a/ieducar/lib/Portabilis/Report/ReportsRenderServerFactory.php b/ieducar/lib/Portabilis/Report/ReportsRenderServerFactory.php index bcd13d9ffe..11957c1bca 100644 --- a/ieducar/lib/Portabilis/Report/ReportsRenderServerFactory.php +++ b/ieducar/lib/Portabilis/Report/ReportsRenderServerFactory.php @@ -40,7 +40,7 @@ public function setSettings($config) * Renderiza o relatório. * * @param Portabilis_Report_ReportCore $report - * @param array $options + * @param array $options * * @return string * diff --git a/ieducar/lib/Portabilis/String/Utils.php b/ieducar/lib/Portabilis/String/Utils.php index 71222e7bb6..52ae220f86 100644 --- a/ieducar/lib/Portabilis/String/Utils.php +++ b/ieducar/lib/Portabilis/String/Utils.php @@ -1,172 +1,121 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/Array/Utils.php'; -/** - * Portabilis_String_Utils class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_String_Utils { - - // wrapper for Portabilis_Array_Utils::merge - protected static function mergeOptions($options, $defaultOptions) { - return Portabilis_Array_Utils::merge($options, $defaultOptions); - } - - - /* splits a string in a array, eg: - - $divisors = array('-', ' '); // or $divisors = '-'; - $options = array('limit' => 2, 'trim' => true); - - Portabilis_String_Utils::split($divisors, '123 - Some value', $options); - => array([0] => '123', [1] => 'Some value'); - */ - public static function split($divisors, $string, $options = array()) { - $result = array($string); - - $defaultOptions = array('limit' => -1, 'trim' => true); - $options = self::mergeOptions($options, $defaultOptions); - - if (! is_array($divisors)) - $divisors = array($divisors); - - foreach ($divisors as $divisor) { - if (is_numeric(strpos($string, $divisor))) { - $divisor = '/' . $divisor . '/'; - $result = preg_split($divisor, $string, $options['limit']); - break; - } +class Portabilis_String_Utils +{ + protected static function mergeOptions($options, $defaultOptions) + { + return Portabilis_Array_Utils::merge($options, $defaultOptions); + } + + /** + * splits a string in a array, eg: + * $divisors = array('-', ' '); // or $divisors = '-'; + * $options = array('limit' => 2, 'trim' => true); + * + * Portabilis_String_Utils::split($divisors, '123 - Some value', $options); + * => array([0] => '123', [1] => 'Some value'); + */ + public static function split($divisors, $string, $options = []) + { + $result = [$string]; + + $defaultOptions = ['limit' => -1, 'trim' => true]; + $options = self::mergeOptions($options, $defaultOptions); + + if (!is_array($divisors)) { + $divisors = [$divisors]; + } + + foreach ($divisors as $divisor) { + if (is_numeric(strpos($string, $divisor))) { + $divisor = '/' . $divisor . '/'; + $result = preg_split($divisor, $string, $options['limit']); + break; + } + } + + if ($options['trim']) { + $result = Portabilis_Array_Utils::trim($result); + } + + return $result; + } + + /** + * scapes a string, adding backslashes before characters that need to be + * quoted, this method is useful to scape values to be inserted via + * database queries. + */ + public static function escape($str) + { + return addslashes($str); + } + + /** + * @deprecated + * + * @param string $str + * @param array $options + * + * @return string + */ + public static function toUtf8($str, $options = []) + { + return $str; + } + + /** + * @deprecated + * + * @param string $str + * @param array $options + * + * @return string + */ + public static function toLatin1($str, $options = []) + { + return $str; + } + + public static function unaccent($str) + { + $fromEncoding = Portabilis_String_Utils::encoding($str); + + return iconv($fromEncoding, 'US-ASCII//TRANSLIT', $str); } - if ($options['trim']) - $result = Portabilis_Array_Utils::trim($result); - - return $result; - } - - - /* scapes a string, adding backslashes before characters that need to be quoted, - this method is useful to scape values to be inserted via database queries. */ - public static function escape($str) { - return addslashes($str); - } - - - /* encodes latin1 strings to utf-8, - this method is useful to return latin1 strings (with accents) stored in db, in json api's. - */ - public static function toUtf8($str, $options = array()) { - // $defaultOptions = array('transform' => false, 'escape' => false, 'convert_html_special_chars' => false); - // $options = self::mergeOptions($options, $defaultOptions); - // - // if ($options['escape']) - // $str = self::escape($str); - // - // if ($options['transform']) - // $str = ucwords(mb_strtolower($str)); - // - // - // $str = utf8_encode($str); - // - // if ($options['convert_html_special_chars']) - // $str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); - - return $str; - } - - - /* encodes utf-8 strings to latin1, - this method is useful to store utf-8 string (with accents) get from json api's, in latin1 db's. - */ - public static function toLatin1($str, $options = array()) { - // $defaultOptions = array('transform' => false, 'escape' => true, 'convert_html_special_chars' => false); - // $options = self::mergeOptions($options, $defaultOptions); - // - // if ($options['escape']) - // $str = self::escape($str); - // - // if ($options['transform']) - // $str = ucwords(mb_strtolower($str)); - // - // - // // apenas converte para latin1, strings utf-8 - // // impedindo assim, converter para latin1 strings que já sejam latin1 - // - // if (Portabilis_String_Utils::encoding($str) == 'UTF-8') - // $str = utf8_decode($str); - // - // if ($options['convert_html_special_chars']) - // $str = htmlspecialchars($str, ENT_QUOTES, ''); - - return $str; - } - - public static function unaccent($str) { - $fromEncoding = Portabilis_String_Utils::encoding($str); - return iconv($fromEncoding, 'US-ASCII//TRANSLIT', $str); - } - - - public static function encoding($str) { - return mb_detect_encoding($str, 'UTF-8, ', $strict = true); - } - - public static function camelize($str) { - return str_replace(' ', '', ucwords(str_replace('_', ' ', $str))); - } - - - public static function underscore($str) { - $words = preg_split('/(?=[A-Z])/', $str, -1, PREG_SPLIT_NO_EMPTY); - return strtolower(implode('_', $words)); - } - - - public static function humanize($str) { - $robotWords = array('_id', 'ref_cod_', 'ref_ref_cod_'); - - foreach ($robotWords as $word) - $str = str_replace($word, '', $str); - - return str_replace('_', ' ', ucwords($str)); - } - - public static function emptyOrNull($str){ - return is_null($str) || empty($str); - } + public static function encoding($str) + { + return mb_detect_encoding($str, 'UTF-8, ', $strict = true); + } + + public static function camelize($str) + { + return str_replace(' ', '', ucwords(str_replace('_', ' ', $str))); + } + + public static function underscore($str) + { + $words = preg_split('/(?=[A-Z])/', $str, -1, PREG_SPLIT_NO_EMPTY); + + return strtolower(implode('_', $words)); + } + + public static function humanize($str) + { + $robotWords = ['_id', 'ref_cod_', 'ref_ref_cod_']; + + foreach ($robotWords as $word) { + $str = str_replace($word, '', $str); + } + + return str_replace('_', ' ', ucwords($str)); + } + + public static function emptyOrNull($str) + { + return is_null($str) || empty($str); + } } diff --git a/ieducar/lib/Portabilis/Utils/CustomLabel.php b/ieducar/lib/Portabilis/Utils/CustomLabel.php index 9a8e0ac1b2..acb93a221a 100644 --- a/ieducar/lib/Portabilis/Utils/CustomLabel.php +++ b/ieducar/lib/Portabilis/Utils/CustomLabel.php @@ -4,10 +4,10 @@ class CustomLabel { - - static protected $instance; + protected static $instance; protected $defaults; + protected $custom; public function __construct($defaultsPath) diff --git a/ieducar/lib/Portabilis/Utils/Database.php b/ieducar/lib/Portabilis/Utils/Database.php index 1247602052..e12b49fab8 100644 --- a/ieducar/lib/Portabilis/Utils/Database.php +++ b/ieducar/lib/Portabilis/Utils/Database.php @@ -1,128 +1,97 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/Array/Utils.php'; -/** - * Portabilis_Utils_Database class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Utils_Database { - - static $_db; - - // wrapper for Portabilis_Array_Utils::merge - protected static function mergeOptions($options, $defaultOptions) { - return Portabilis_Array_Utils::merge($options, $defaultOptions); - } - - public static function db() { - if (! isset(self::$_db)) - self::$_db = new clsBanco(); - - return self::$_db; - } - - public static function fetchPreparedQuery($sql, $options = array()) { - $result = array(); - - $defaultOptions = array('params' => array(), - 'show_errors' => true, - 'return_only' => '', - 'messenger' => null); - - $options = self::mergeOptions($options, $defaultOptions); - - // options validations - //if ($options['show_errors'] and is_null($options['messenger'])) - // throw new Exception("When 'show_errors' is true you must pass the option messenger too."); - - - try { - if (self::db()->execPreparedQuery($sql, $options['params']) != false) { - while (self::db()->ProximoRegistro()) - $result[] = self::db()->Tupla(); - - if (in_array($options['return_only'], array('first-line', 'first-row', 'first-record')) and count($result) > 0) - $result = $result[0]; - elseif ($options['return_only'] == 'first-field' and count($result) > 0 and count($result[0]) > 0) - $result = $result[0][0]; - } - } - catch(Exception $e) { - if ($options['show_errors'] and ! is_null($options['messenger'])) - $options['messenger']->append($e->getMessage(), 'error'); - else - throw $e; - } +class Portabilis_Utils_Database +{ + public static $_db; - return $result; - } - - // helper para consultas que buscam apenas o primeiro campo, - // considera o segundo argumento o array de options esperado por fetchPreparedQuery - // a menos que este não possua um chave params ou não seja um array, - // neste caso o considera como params - public static function selectField($sql, $paramsOrOptions = array()) { + protected static function mergeOptions($options, $defaultOptions) + { + return Portabilis_Array_Utils::merge($options, $defaultOptions); + } - if (! is_array($paramsOrOptions) || ! isset($paramsOrOptions['params'])) - $paramsOrOptions = array('params' => $paramsOrOptions); + public static function db() + { + if (!isset(self::$_db)) { + self::$_db = new clsBanco(); + } - $paramsOrOptions['return_only'] = 'first-field'; - return self::fetchPreparedQuery($sql, $paramsOrOptions); - } + return self::$_db; + } - // helper para consultas que buscam apenas a primeira linha - // considera o segundo argumento o array de options esperado por fetchPreparedQuery - // a menos que este não possua um chave params ou não seja um array, - // neste caso o considera como params - public static function selectRow($sql, $paramsOrOptions = array()) { + public static function fetchPreparedQuery($sql, $options = []) + { + $result = []; + + $defaultOptions = [ + 'params' => [], + 'show_errors' => true, + 'return_only' => '', + 'messenger' => null + ]; + + $options = self::mergeOptions($options, $defaultOptions); + + try { + if (self::db()->execPreparedQuery($sql, $options['params']) != false) { + while (self::db()->ProximoRegistro()) { + $result[] = self::db()->Tupla(); + } + + if (in_array($options['return_only'], ['first-line', 'first-row', 'first-record']) and count($result) > 0) { + $result = $result[0]; + } elseif ($options['return_only'] == 'first-field' and count($result) > 0 and count($result[0]) > 0) { + $result = $result[0][0]; + } + } + } catch (Exception $e) { + if ($options['show_errors'] and !is_null($options['messenger'])) { + $options['messenger']->append($e->getMessage(), 'error'); + } else { + throw $e; + } + } + + return $result; + } - if (! is_array($paramsOrOptions) || ! isset($paramsOrOptions['params'])) - $paramsOrOptions = array('params' => $paramsOrOptions); + /** + * helper para consultas que buscam apenas o primeiro campo, considera o + * segundo argumento o array de options esperado por fetchPreparedQuery a + * menos que este não possua um chave params ou não seja um array, neste + * caso o considera como params + */ + public static function selectField($sql, $paramsOrOptions = []) + { + if (!is_array($paramsOrOptions) || !isset($paramsOrOptions['params'])) { + $paramsOrOptions = ['params' => $paramsOrOptions]; + } + + $paramsOrOptions['return_only'] = 'first-field'; + + return self::fetchPreparedQuery($sql, $paramsOrOptions); + } - $paramsOrOptions['return_only'] = 'first-row'; - return self::fetchPreparedQuery($sql, $paramsOrOptions); - } + /** + * helper para consultas que buscam apenas a primeira linha considera o + * segundo argumento o array de options esperado por fetchPreparedQuery a + * menos que este não possua um chave params ou não seja um array, neste + * caso o considera como params + */ + public static function selectRow($sql, $paramsOrOptions = []) + { + if (!is_array($paramsOrOptions) || !isset($paramsOrOptions['params'])) { + $paramsOrOptions = ['params' => $paramsOrOptions]; + } + + $paramsOrOptions['return_only'] = 'first-row'; + + return self::fetchPreparedQuery($sql, $paramsOrOptions); + } - public static function arrayToPgArray(array $value):string - { - return "'{" . implode(',', $value) . "}'"; - } + public static function arrayToPgArray(array $value): string + { + return '\'{' . implode(',', $value) . '}\''; + } } diff --git a/ieducar/lib/Portabilis/Utils/DeprecatedXmlApi.php b/ieducar/lib/Portabilis/Utils/DeprecatedXmlApi.php index f82686cfe8..c5592a96af 100644 --- a/ieducar/lib/Portabilis/Utils/DeprecatedXmlApi.php +++ b/ieducar/lib/Portabilis/Utils/DeprecatedXmlApi.php @@ -1,64 +1,27 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/Utils/User.php'; -/** - * Portabilis_Utils_DeprecatedXmlApi class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Utils_DeprecatedXmlApi { - - public static function returnEmptyQueryUnlessUserIsLoggedIn($xmlns = 'sugestoes', $rootNodeName = 'query') { - if (Portabilis_Utils_User::loggedIn() != true) - Portabilis_Utils_DeprecatedXmlApi::returnEmptyQuery($xmlns, $rootNodeName, 'Login required'); - } - - public static function returnEmptyQueryForDisabledApi($xmlns = 'sugestoes', $rootNodeName = 'query'){ - Portabilis_Utils_DeprecatedXmlApi::returnEmptyQuery($xmlns, $rootNodeName, 'Disabled API'); - } - - public static function returnEmptyQuery($xmlns = 'sugestoes', $rootNodeName = 'query', $comment = ''){ - $emptyQuery = "" . - "" . - "<$rootNodeName xmlns='$xmlns'>"; - - die($emptyQuery); - } +class Portabilis_Utils_DeprecatedXmlApi +{ + public static function returnEmptyQueryUnlessUserIsLoggedIn($xmlns = 'sugestoes', $rootNodeName = 'query') + { + if (Portabilis_Utils_User::loggedIn() != true) { + Portabilis_Utils_DeprecatedXmlApi::returnEmptyQuery($xmlns, $rootNodeName, 'Login required'); + } + } + + public static function returnEmptyQueryForDisabledApi($xmlns = 'sugestoes', $rootNodeName = 'query') + { + Portabilis_Utils_DeprecatedXmlApi::returnEmptyQuery($xmlns, $rootNodeName, 'Disabled API'); + } + + public static function returnEmptyQuery($xmlns = 'sugestoes', $rootNodeName = 'query', $comment = '') + { + $emptyQuery = '' + . "" + . "<$rootNodeName xmlns='$xmlns'>"; + + die($emptyQuery); + } } diff --git a/ieducar/lib/Portabilis/Utils/Float.php b/ieducar/lib/Portabilis/Utils/Float.php index 5e3a830529..11bb546287 100644 --- a/ieducar/lib/Portabilis/Utils/Float.php +++ b/ieducar/lib/Portabilis/Utils/Float.php @@ -1,77 +1,42 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/Array/Utils.php'; -/** - * Portabilis_Utils_Float class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Utils_Float { - - // wrapper for Portabilis_Array_Utils::merge - protected static function mergeOptions($options, $defaultOptions) { - return Portabilis_Array_Utils::merge($options, $defaultOptions); - } - - - /* Limita as casas decimais de um numero float, SEM arredonda-lo, - ex: para 4.96, usando limit = 1, retornará 4.9 e não 5. */ - public static function limitDecimal($value, $options = array()) { - if (! is_numeric($value)) - throw new Exception("Value must be numeric!"); - elseif(is_integer($value)) - return (float)$value; - - $locale = localeconv(); - - $defaultOptions = array('limit' => 2, - 'decimal_point' => $locale['decimal_point'], - 'thousands_sep' => $locale['thousands_sep']); - - $options = self::mergeOptions($options, $defaultOptions); - - - // split the values after and before the decimal point. - $digits = explode($options['decimal_point'], (string)$value); - - // limit the decimal using the limit option (defaults to 2), eg: .96789 will be limited to .96 - $digits[1] = substr($digits[1], 0, $options['limit']); - - // join the the digits and convert it to float, eg: '4' and '96', will be '4.96' - return (float)($digits[0] . '.' . $digits[1]); - } +class Portabilis_Utils_Float +{ + protected static function mergeOptions($options, $defaultOptions) + { + return Portabilis_Array_Utils::merge($options, $defaultOptions); + } + + /** + * Limita as casas decimais de um numero float, SEM arredonda-lo, ex: para + * 4.96, usando limit = 1, retornará 4.9 e não 5. + */ + public static function limitDecimal($value, $options = []) + { + if (!is_numeric($value)) { + throw new Exception('Value must be numeric!'); + } elseif (is_integer($value)) { + return (float) $value; + } + + $locale = localeconv(); + + $defaultOptions = ['limit' => 2, + 'decimal_point' => $locale['decimal_point'], + 'thousands_sep' => $locale['thousands_sep'] + ]; + + $options = self::mergeOptions($options, $defaultOptions); + + // split the values after and before the decimal point. + $digits = explode($options['decimal_point'], (string) $value); + + // limit the decimal using the limit option (defaults to 2), eg: .96789 will be limited to .96 + $digits[1] = substr($digits[1], 0, $options['limit']); + + // join the the digits and convert it to float, eg: '4' and '96', will be '4.96' + return (float) ($digits[0] . '.' . $digits[1]); + } } diff --git a/ieducar/lib/Portabilis/Utils/ReCaptcha.php b/ieducar/lib/Portabilis/Utils/ReCaptcha.php index 36e2bd59fa..242ee626e8 100644 --- a/ieducar/lib/Portabilis/Utils/ReCaptcha.php +++ b/ieducar/lib/Portabilis/Utils/ReCaptcha.php @@ -2,8 +2,8 @@ require_once 'vendor/autoload.php'; -class Portabilis_Utils_ReCaptcha { - +class Portabilis_Utils_ReCaptcha +{ public static function getWidget() { $config = $GLOBALS['coreExt']['Config']->app->recaptcha; diff --git a/ieducar/lib/Portabilis/Utils/User.php b/ieducar/lib/Portabilis/Utils/User.php index 8f66e94432..d490a25e8c 100644 --- a/ieducar/lib/Portabilis/Utils/User.php +++ b/ieducar/lib/Portabilis/Utils/User.php @@ -1,198 +1,187 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * Portabilis_Utils_User class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Utils_User { - - static $_currentUserId; - static $_nivelAcesso; - static $_permissoes; - - static function currentUserId() { - if (! isset(self::$_currentUserId)) { - @session_start(); - self::$_currentUserId = $_SESSION['id_pessoa']; - session_write_close(); +class Portabilis_Utils_User +{ + public static $_currentUserId; + public static $_nivelAcesso; + public static $_permissoes; + + public static function currentUserId() + { + if (!isset(self::$_currentUserId)) { + @session_start(); + self::$_currentUserId = $_SESSION['id_pessoa']; + session_write_close(); + } + + return self::$_currentUserId; } - return self::$_currentUserId; - } - - static function redirectToLogoff() { - header('Location: /intranet/logof.php'); - } - - - static function loggedIn(){ - return is_numeric(self::currentUserId()); - } - - // database helpers - - static function loadUsingCredentials($username, $password) { - $sql = "SELECT ref_cod_pessoa_fj FROM portal.funcionario WHERE matricula = $1 and senha = $2"; - $options = array('params' => array($username, $password), 'show_errors' => false, 'return_only' => 'first-field'); - $userId = self::fetchPreparedQuery($sql, $options); - - if (is_numeric($userId)) - return self::load($userId); - - return null; - } - - // TODO usar modules/Usuario/Model/Funcionario ao invés de executar select - static function load($id) { - if ($id == 'current_user') - $id = self::currentUserId(); - elseif (! is_numeric($id)) - throw new Exception("'$id' is not a valid id, please send a numeric value or a string 'current_user'"); - - $sql = "SELECT ref_cod_pessoa_fj as id, opcao_menu, ref_cod_setor_new, tipo_menu, matricula, email, status_token, - ativo, proibido, tempo_expira_conta, data_reativa_conta, tempo_expira_senha, data_troca_senha, - ip_logado as ip_ultimo_acesso, data_login FROM portal.funcionario WHERE ref_cod_pessoa_fj = $1"; - - $options = array('params' => array($id), 'show_errors' => false, 'return_only' => 'first-line'); - $user = self::fetchPreparedQuery($sql, $options); - $user['super'] = $GLOBALS['coreExt']['Config']->app->superuser == $user['matricula']; - - - /* considera como expirado caso usuario não admin e data_reativa_conta + tempo_expira_conta <= now - obs: ao salvar drh > cadastro funcionario, seta data_reativa_conta = now */ - $user['expired_account'] = ! $user['super'] && ! empty($user['tempo_expira_conta']) && - ! empty($user['data_reativa_conta']) && - time() - strtotime($user['data_reativa_conta']) > $user['tempo_expira_conta'] * 60 * 60 * 24; - - - // considera o periodo para expiração de senha definido nas configs, caso o tenha sido feito. - $tempoExpiraSenha = $GLOBALS['coreExt']['Config']->app->user_accounts->default_password_expiration_period; - - if (! is_numeric($tempoExpiraSenha)) - $tempoExpiraSenha = $user['tempo_expira_senha']; - - /* considera como expirado caso data_troca_senha + tempo_expira_senha <= now */ - $user['expired_password'] = ! empty($user['data_troca_senha']) && ! empty($tempoExpiraSenha) && - time() - strtotime($user['data_troca_senha']) > $tempoExpiraSenha * 60 * 60 * 24; - - return $user; - } - - - static function disableAccount($userId) { - $sql = "UPDATE portal.funcionario SET ativo = 0 WHERE ref_cod_pessoa_fj = $1"; - $options = array('params' => array($userId), 'show_errors' => false); - - self::fetchPreparedQuery($sql, $options); - } + public static function redirectToLogoff() + { + header('Location: /intranet/logof.php'); + } + public static function loggedIn() + { + return is_numeric(self::currentUserId()); + } - /* - Destroi determinado tipo de status_token de um usuário, como ocorre por exemplo após fazer login, - onde solicitações de redefinição de senha em aberto são destruidas. - */ - static function destroyStatusTokenFor($userId, $withType) { - $sql = "UPDATE portal.funcionario set status_token = '' WHERE ref_cod_pessoa_fj = $1 and status_token like $2"; - $options = array('params' => array($userId, "$withType-%"), 'show_errors' => false); + public static function loadUsingCredentials($username, $password) + { + $sql = 'SELECT ref_cod_pessoa_fj FROM portal.funcionario WHERE matricula = $1 and senha = $2'; - self::fetchPreparedQuery($sql, $options); - } + $options = ['params' => [$username, $password], 'show_errors' => false, 'return_only' => 'first-field']; + $userId = self::fetchPreparedQuery($sql, $options); - static function logAccessFor($userId, $clientIP) { - $sql = "UPDATE portal.funcionario SET ip_logado = '$clientIP', data_login = NOW() WHERE ref_cod_pessoa_fj = $1"; - $options = array('params' => array($userId), 'show_errors' => false); + if (is_numeric($userId)) { + return self::load($userId); + } - self::fetchPreparedQuery($sql, $options); - } + return null; + } + public static function load($id) + { + if ($id == 'current_user') { + $id = self::currentUserId(); + } elseif (!is_numeric($id)) { + throw new Exception("'$id' is not a valid id, please send a numeric value or a string 'current_user'"); + } + + $sql = ' + SELECT + ref_cod_pessoa_fj as id, + opcao_menu, + ref_cod_setor_new, + tipo_menu, + matricula, + email, + status_token, + ativo, + proibido, + tempo_expira_conta, + data_reativa_conta, + tempo_expira_senha, + data_troca_senha, + ip_logado as ip_ultimo_acesso, + data_login + FROM portal.funcionario + WHERE ref_cod_pessoa_fj = $1 + '; + + $options = ['params' => [$id], 'show_errors' => false, 'return_only' => 'first-line']; + $user = self::fetchPreparedQuery($sql, $options); + $user['super'] = $GLOBALS['coreExt']['Config']->app->superuser == $user['matricula']; + + // considera como expirado caso usuario não admin e data_reativa_conta + tempo_expira_conta <= now + // obs: ao salvar drh > cadastro funcionario, seta data_reativa_conta = now + + $user['expired_account'] = !$user['super'] + && !empty($user['tempo_expira_conta']) + && !empty($user['data_reativa_conta']) + && time() - strtotime($user['data_reativa_conta']) > $user['tempo_expira_conta'] * 60 * 60 * 24; + + // considera o periodo para expiração de senha definido nas configs, caso o tenha sido feito. + + $tempoExpiraSenha = $GLOBALS['coreExt']['Config']->app->user_accounts->default_password_expiration_period; + + if (!is_numeric($tempoExpiraSenha)) { + $tempoExpiraSenha = $user['tempo_expira_senha']; + } + + /* considera como expirado caso data_troca_senha + tempo_expira_senha <= now */ + + $user['expired_password'] = !empty($user['data_troca_senha']) + && !empty($tempoExpiraSenha) + && time() - strtotime($user['data_troca_senha']) > $tempoExpiraSenha * 60 * 60 * 24; + + return $user; + } + public static function disableAccount($userId) + { + $sql = 'UPDATE portal.funcionario SET ativo = 0 WHERE ref_cod_pessoa_fj = $1'; + $options = ['params' => [$userId], 'show_errors' => false]; - // permissões + self::fetchPreparedQuery($sql, $options); + } - static function getClsPermissoes() { - if (! isset(self::$_permissoes)) - self::$_permissoes = new clsPermissoes(); + /** + * Destroi determinado tipo de status_token de um usuário, como ocorre por + * exemplo após fazer login, onde solicitações de redefinição de senha em + * aberto são destruidas. + */ + public static function destroyStatusTokenFor($userId, $withType) + { + $sql = 'UPDATE portal.funcionario set status_token = \'\' WHERE ref_cod_pessoa_fj = $1 and status_token like $2'; + $options = ['params' => [$userId, "$withType-%"], 'show_errors' => false]; + + self::fetchPreparedQuery($sql, $options); + } - return self::$_permissoes; - } + public static function logAccessFor($userId, $clientIP) + { + $sql = "UPDATE portal.funcionario SET ip_logado = '$clientIP', data_login = NOW() WHERE ref_cod_pessoa_fj = $1"; + $options = ['params' => [$userId], 'show_errors' => false]; + self::fetchPreparedQuery($sql, $options); + } - static function getNivelAcesso() { - if (! isset(self::$_nivelAcesso)) - self::$_nivelAcesso = self::getClsPermissoes()->nivel_acesso(self::currentUserId()); + public static function getClsPermissoes() + { + if (!isset(self::$_permissoes)) { + self::$_permissoes = new clsPermissoes(); + } - return self::$_nivelAcesso; - } + return self::$_permissoes; + } + public static function getNivelAcesso() + { + if (!isset(self::$_nivelAcesso)) { + self::$_nivelAcesso = self::getClsPermissoes()->nivel_acesso(self::currentUserId()); + } - # TODO verificar se é possivel usar a logica de App_Model_NivelAcesso - static function hasNivelAcesso($nivelAcessoType) { - $niveisAcesso = array('POLI_INSTITUCIONAL' => 1, - 'INSTITUCIONAL' => 2, - 'SOMENTE_ESCOLA' => 4, - 'SOMENTE_BIBLIOTECA' => 8); + return self::$_nivelAcesso; + } - if (! isset($niveisAcesso[$nivelAcessoType])) - throw new CoreExt_Exception("Nivel acesso '$nivelAcessoType' não definido."); + public static function hasNivelAcesso($nivelAcessoType) + { + $niveisAcesso = [ + 'POLI_INSTITUCIONAL' => 1, + 'INSTITUCIONAL' => 2, + 'SOMENTE_ESCOLA' => 4, + 'SOMENTE_BIBLIOTECA' => 8 + ]; - return self::getNivelAcesso() == $niveisAcesso[$nivelAcessoType]; - } + if (!isset($niveisAcesso[$nivelAcessoType])) { + throw new CoreExt_Exception("Nivel acesso '$nivelAcessoType' não definido."); + } + return self::getNivelAcesso() == $niveisAcesso[$nivelAcessoType]; + } - static function canAccessEscola($id) { + public static function canAccessEscola($id) + { + if (self::hasNivelAcesso('POLI_INSTITUCIONAL') || self::hasNivelAcesso('INSTITUCIONAL')) { + return true; + } - if (self::hasNivelAcesso('POLI_INSTITUCIONAL') || - self::hasNivelAcesso('INSTITUCIONAL')) - return true; + $escolas = App_Model_IedFinder::getEscolasUser(self::currentUserId()); - $escolas = App_Model_IedFinder::getEscolasUser(self::currentUserId()); + foreach ($escolas as $escola) { + if ($escola['ref_cod_escola'] == $id) { + return true; + } + } - foreach ($escolas as $escola) { - if ($escola['ref_cod_escola'] == $id) return true; + return false; } - return false; - } - - - // wrappers for Portabilis*Utils* - - protected static function fetchPreparedQuery($sql, $options = array()) { - return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - } -} \ No newline at end of file + protected static function fetchPreparedQuery($sql, $options = []) + { + return Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + } +} diff --git a/ieducar/lib/Portabilis/Utils/Validation.php b/ieducar/lib/Portabilis/Utils/Validation.php index 66c3fe48a8..9602a8f9a3 100644 --- a/ieducar/lib/Portabilis/Utils/Validation.php +++ b/ieducar/lib/Portabilis/Utils/Validation.php @@ -1,98 +1,60 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/Utils/User.php'; -/** - * Portabilis_Utils_Validation class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Utils_Validation { - - public static function validatesCpf($cpf) { - $cpf = preg_replace('/[^0-9]/', '', (string)$cpf); - - if (strlen($cpf) != 11) - return false; +class Portabilis_Utils_Validation +{ + public static function validatesCpf($cpf) + { + $cpf = preg_replace('/[^0-9]/', '', (string) $cpf); - $cpfsInvalidos = array( - '00000000000', - '11111111111', - '22222222222', - '33333333333', - '44444444444', - '55555555555', - '66666666666', - '77777777777', - '88888888888', - '99999999999' - ); + if (strlen($cpf) != 11) { + return false; + } - if (in_array($cpf, $cpfsInvalidos)) { - return false; - } - - // calcula primeiro dígito verificador - $soma = 0; + $cpfsInvalidos = [ + '00000000000', + '11111111111', + '22222222222', + '33333333333', + '44444444444', + '55555555555', + '66666666666', + '77777777777', + '88888888888', + '99999999999' + ]; - for ($i = 0; $i < 9; $i++) - $soma += ((10 - $i) * $cpf[$i]); + if (in_array($cpf, $cpfsInvalidos)) { + return false; + } - $primeiroDigito = 11 - ($soma % 11); + // calcula primeiro dígito verificador + $soma = 0; - if ($primeiroDigito >= 10) - $primeiroDigito = 0; + for ($i = 0; $i < 9; $i++) { + $soma += ((10 - $i) * $cpf[$i]); + } + $primeiroDigito = 11 - ($soma % 11); - // calcula segundo dígito verificador - $soma = 0; + if ($primeiroDigito >= 10) { + $primeiroDigito = 0; + } - for ($i = 0; $i < 10; $i++) - $soma += ((11 - $i) * $cpf[$i]); + // calcula segundo dígito verificador + $soma = 0; - $segundoDigito = 11 - ($soma % 11); + for ($i = 0; $i < 10; $i++) { + $soma += ((11 - $i) * $cpf[$i]); + } - if ($segundoDigito >= 10) - $segundoDigito = 0; + $segundoDigito = 11 - ($soma % 11); + if ($segundoDigito >= 10) { + $segundoDigito = 0; + } - - return ($primeiroDigito == $cpf[9] && $segundoDigito == $cpf[10]); - } + return ($primeiroDigito == $cpf[9] && $segundoDigito == $cpf[10]); + } } diff --git a/ieducar/lib/Portabilis/Validator.php b/ieducar/lib/Portabilis/Validator.php index 12330c0c5f..1ad9d9ead9 100644 --- a/ieducar/lib/Portabilis/Validator.php +++ b/ieducar/lib/Portabilis/Validator.php @@ -1,157 +1,123 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'include/clsBanco.inc.php'; require_once 'CoreExt/Exception.php'; require_once 'lib/Portabilis/Utils/Database.php'; -/** - * Portabilis_Validator class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_Validator { - - public function __construct(&$messenger) { - $this->messenger = $messenger; - } - - - // TODO refatorar todos metodos, para não receber mais argumento $raiseException* +class Portabilis_Validator +{ + public function __construct(&$messenger) + { + $this->messenger = $messenger; + } - /* TODO refatorar todos metodos, para não receber mais argumento $addMsg* - caso $msg falso pode-se disparar erro */ + public function validatesPresenceOf(&$value, $name, $raiseExceptionOnFail = false, $msg = '', $addMsgOnEmpty = true) + { + if (!isset($value) || (empty($value) && !is_numeric($value))) { + if ($addMsgOnEmpty) { + $msg = empty($msg) ? "É necessário receber uma variavel '$name'" : $msg; + $this->messenger->append($msg); + } - public function validatesPresenceOf(&$value, $name, $raiseExceptionOnFail = false, $msg = '', $addMsgOnEmpty = true){ - if (! isset($value) || (empty($value) && !is_numeric($value))){ - if ($addMsgOnEmpty) - { - $msg = empty($msg) ? "É necessário receber uma variavel '$name'" : $msg; - $this->messenger->append($msg); - } + if ($raiseExceptionOnFail) { + throw new CoreExt_Exception($msg); + } - if ($raiseExceptionOnFail) - throw new CoreExt_Exception($msg); + return false; + } - return false; + return true; } - return true; - } + public function validatesValueIsNumeric(&$value, $name, $raiseExceptionOnFail = false, $msg = '', $addMsgOnError = true) + { + if (!is_numeric($value)) { + if ($addMsgOnError) { + $msg = empty($msg) ? "O valor recebido para variavel '$name' deve ser numerico" : $msg; + $this->messenger->append($msg); + } - public function validatesValueIsNumeric(&$value, $name, $raiseExceptionOnFail = false, $msg = '', $addMsgOnError = true){ - if (! is_numeric($value)){ - if ($addMsgOnError) - { - $msg = empty($msg) ? "O valor recebido para variavel '$name' deve ser numerico" : $msg; - $this->messenger->append($msg); - } + if ($raiseExceptionOnFail) { + throw new CoreExt_Exception($msg); + } - if ($raiseExceptionOnFail) - throw new CoreExt_Exception($msg); + return false; + } - return false; + return true; } - return true; - } - - public function validatesValueIsArray(&$value, $name, $raiseExceptionOnFail = false, $msg = '', $addMsgOnError = true){ + public function validatesValueIsArray(&$value, $name, $raiseExceptionOnFail = false, $msg = '', $addMsgOnError = true) + { + if (!is_array($value)) { + if ($addMsgOnError) { + $msg = empty($msg) ? "Deve ser recebido uma lista de '$name'" : $msg; + $this->messenger->append($msg); + } - if (! is_array($value)){ - if ($addMsgOnError) { - $msg = empty($msg) ? "Deve ser recebido uma lista de '$name'" : $msg; - $this->messenger->append($msg); - } + if ($raiseExceptionOnFail) { + throw new CoreExt_Exception($msg); + } - if ($raiseExceptionOnFail) - throw new CoreExt_Exception($msg); + return false; + } - return false; + return true; } - return true; - } + public function validatesValueInSetOf(&$value, $setExpectedValues, $name, $raiseExceptionOnFail = false, $msg = '') + { + if (!empty($setExpectedValues) && !in_array($value, $setExpectedValues)) { + $msg = empty($msg) ? "Valor recebido na variavel '$name' é invalido" : $msg; + $this->messenger->append($msg); - public function validatesValueInSetOf(&$value, $setExpectedValues, $name, $raiseExceptionOnFail = false, $msg = ''){ - if (! empty($setExpectedValues) && ! in_array($value, $setExpectedValues)){ - $msg = empty($msg) ? "Valor recebido na variavel '$name' é invalido" : $msg; - $this->messenger->append($msg); + if ($raiseExceptionOnFail) { + throw new CoreExt_Exception($msg); + } - if ($raiseExceptionOnFail) - throw new CoreExt_Exception($msg); + return false; + } - return false; + return true; } - return true; - } + public function validatesValueIsInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnFail = true, $addMsgOnError = true) + { + $sql = "select 1 from $schemaName.$tableName where $fieldName = $1 limit 1"; - public function validatesValueIsInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnFail = true, $addMsgOnError = true){ - $sql = "select 1 from $schemaName.$tableName where $fieldName = $1 limit 1"; + if (Portabilis_Utils_Database::selectField($sql, $value) != 1) { + if ($addMsgOnError) { + $msg = "O valor informado {$value} para $tableName, não esta presente no banco de dados."; + $this->messenger->append($msg); + } - if (Portabilis_Utils_Database::selectField($sql, $value) != 1){ - if ($addMsgOnError) { - $msg = "O valor informado {$value} para $tableName, não esta presente no banco de dados."; - $this->messenger->append($msg); - } + if ($raiseExceptionOnFail) { + throw new CoreExt_Exception($msg); + } - if ($raiseExceptionOnFail) - throw new CoreExt_Exception($msg); + return false; + } - return false; + return true; } - return true; - } + public function validatesValueNotInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnFail = true, $addMsgOnError = true) + { + $sql = "select 1 from $schemaName.$tableName where $fieldName = $1 limit 1"; - public function validatesValueNotInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnFail = true, $addMsgOnError = true){ - $sql = "select 1 from $schemaName.$tableName where $fieldName = $1 limit 1"; + if (Portabilis_Utils_Database::selectField($sql, $value) == 1) { + if ($addMsgOnError) { + $msg = "O valor informado {$value} para $tableName já existe no banco de dados."; + $this->messenger->append($msg); + } - if (Portabilis_Utils_Database::selectField($sql, $value) == 1) { - if ($addMsgOnError) { - $msg = "O valor informado {$value} para $tableName já existe no banco de dados."; - $this->messenger->append($msg); - } + if ($raiseExceptionOnFail) { + throw new CoreExt_Exception($msg); + } - if ($raiseExceptionOnFail) - throw new CoreExt_Exception($msg); + return false; + } - return false; + return true; } - - return true; - } -} \ No newline at end of file +} diff --git a/ieducar/lib/Portabilis/View/Helper/Application.php b/ieducar/lib/Portabilis/View/Helper/Application.php index 99d494bcdd..9cd6412b9c 100644 --- a/ieducar/lib/Portabilis/View/Helper/Application.php +++ b/ieducar/lib/Portabilis/View/Helper/Application.php @@ -1,195 +1,158 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'CoreExt/View/Helper/Abstract.php'; require_once 'Portabilis/Assets/Version.php'; -/** - * ApplicationHelper class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ - -class Portabilis_View_Helper_Application extends CoreExt_View_Helper_Abstract { - - // previne carregar mais de uma vez o mesmo asset js ou css - protected static $javascriptsLoaded = array(); - protected static $stylesheetsLoaded = array(); - - - /** - * Construtor singleton. - */ - protected function __construct() - { - } - - - /** - * Retorna uma instância singleton. - * @return CoreExt_View_Helper_Abstract - */ - public static function getInstance() - { - return self::_getInstance(__CLASS__); - } - - - - /** - * Adiciona elementos chamadas scripts javascript para instancia da view recebida, exemplo: - * - * - * $applicationHelper->javascript($viewInstance, array('/modules/ModuleName/Assets/Javascripts/ScriptName.js', '...')); - * - * - * @param object $viewInstance Istancia da view a ser carregado os scripts. - * @param array ou string $files Lista de scripts a serem carregados. - * @return null - */ - public static function loadJavascript($viewInstance, $files, $appendAssetsVersionParam = true) { - if (! is_array($files)) - $files = array($files); - - foreach ($files as $file) { - // somente carrega o asset uma vez - if (! in_array($file, self::$javascriptsLoaded)) { - self::$javascriptsLoaded[] = $file; - - if ($appendAssetsVersionParam) - $file .= '?assets_version=' . Portabilis_Assets_Version::VERSION; - - $viewInstance->appendOutput(""); - } - } - } - - - /** - * Adiciona links css para instancia da view recebida, exemplo: - * - * - * $applicationHelper->stylesheet($viewInstance, array('/modules/ModuleName/Assets/Stylesheets/StyleName.css', '...')); - * - * - * @param object $viewInstance1 Istancia da view a ser adicionado os links para os estilos. - * @param array ou string $files Lista de estilos a serem carregados. - * @return null - */ - public static function loadStylesheet($viewInstance, $files, $appendAssetsVersionParam = true) { - if (! is_array($files)) - $files = array($files); - - foreach ($files as $file) { - // somente carrega o asset uma vez - if (! in_array($file, self::$stylesheetsLoaded)) { - self::$stylesheetsLoaded[] = $file; - - if ($appendAssetsVersionParam) - $file .= '?assets_version=' . Portabilis_Assets_Version::VERSION; - - $viewInstance->appendOutput(""); - } - } - } - - - public static function embedJavascript($viewInstance, $script, $afterReady = false) { - if ($afterReady) { +class Portabilis_View_Helper_Application extends CoreExt_View_Helper_Abstract +{ + protected static $javascriptsLoaded = []; + protected static $stylesheetsLoaded = []; - $script = "(function($){ - $(document).ready(function(){ - $script - }); - })(jQuery);"; + /** + * Construtor singleton. + */ + protected function __construct() + { } - $viewInstance->appendOutput(""); - } - - - public static function embedStylesheet($viewInstance, $css) { - $viewInstance->appendOutput(""); - } - - public static function embedJavascriptToFixupFieldsWidth($viewInstance) { - - Portabilis_View_Helper_Application::loadJavascript( - $viewInstance, '/modules/Portabilis/Assets/Javascripts/Utils.js' - ); + /** + * Retorna uma instância singleton. + * + * @return CoreExt_View_Helper_Abstract + */ + public static function getInstance() + { + return self::_getInstance(__CLASS__); + } - Portabilis_View_Helper_Application::embedJavascript( - $viewInstance, 'fixupFieldsWidth();', $afterReady = true - ); + /** + * Adiciona elementos chamadas scripts javascript para instancia da view recebida, exemplo: + * + * + * $applicationHelper->javascript($viewInstance, array('/modules/ModuleName/Assets/Javascripts/ScriptName.js', '...')); + * + * + * @param object $viewInstance Istancia da view a ser carregado os scripts. + * @param array|string $files Lista de scripts a serem carregados. + * + * @return null + */ + public static function loadJavascript($viewInstance, $files, $appendAssetsVersionParam = true) + { + if (!is_array($files)) { + $files = [$files]; + } + + foreach ($files as $file) { + if (!in_array($file, self::$javascriptsLoaded)) { + self::$javascriptsLoaded[] = $file; + + if ($appendAssetsVersionParam) { + $file .= '?assets_version=' . Portabilis_Assets_Version::VERSION; + } + + $viewInstance->appendOutput(""); + } + } + } - } + /** + * Adiciona links css para instancia da view recebida, exemplo: + * + * + * $applicationHelper->stylesheet($viewInstance, array('/modules/ModuleName/Assets/Stylesheets/StyleName.css', '...')); + * + * + * @param $viewInstance + * @param array|string $files Lista de estilos a serem carregados. + * @param bool $appendAssetsVersionParam + * + * @return null + */ + public static function loadStylesheet($viewInstance, $files, $appendAssetsVersionParam = true) + { + if (!is_array($files)) { + $files = [$files]; + } + + foreach ($files as $file) { + if (!in_array($file, self::$stylesheetsLoaded)) { + self::$stylesheetsLoaded[] = $file; + + if ($appendAssetsVersionParam) { + $file .= '?assets_version=' . Portabilis_Assets_Version::VERSION; + } + + $viewInstance->appendOutput(""); + } + } + } - // load lib helpers + public static function embedJavascript($viewInstance, $script, $afterReady = false) + { + if ($afterReady) { + $script = " + (function($){ + $(document).ready(function(){ + $script + }); + })(jQuery); + "; + } + + $viewInstance->appendOutput(""); + } - public static function loadJQueryLib($viewInstance) { - self::loadJavascript($viewInstance, 'scripts/jquery/jquery-1.8.3.min.js', false); - self::embedJavascript($viewInstance, "if (typeof(\$j) == 'undefined') { var \$j = jQuery.noConflict(); }"); - } + public static function embedStylesheet($viewInstance, $css) + { + $viewInstance->appendOutput(""); + } + public static function embedJavascriptToFixupFieldsWidth($viewInstance) + { + Portabilis_View_Helper_Application::loadJavascript( + $viewInstance, + '/modules/Portabilis/Assets/Javascripts/Utils.js' + ); + + Portabilis_View_Helper_Application::embedJavascript( + $viewInstance, + 'fixupFieldsWidth();', + $afterReady = true + ); + } - public static function loadJQueryFormLib($viewInstance) { - self::loadJavascript($viewInstance, 'scripts/jquery/jquery.form.js', false); - } + public static function loadJQueryLib($viewInstance) + { + self::loadJavascript($viewInstance, 'scripts/jquery/jquery-1.8.3.min.js', false); + self::embedJavascript($viewInstance, 'if (typeof($j) == \'undefined\') { var $j = jQuery.noConflict(); }'); + } + public static function loadJQueryFormLib($viewInstance) + { + self::loadJavascript($viewInstance, 'scripts/jquery/jquery.form.js', false); + } - public static function loadJQueryUiLib($viewInstance) { - self::loadJavascript($viewInstance, 'scripts/jquery/jquery-ui.min-1.9.2/js/jquery-ui-1.9.2.custom.min.js', true); - self::loadStylesheet($viewInstance, 'scripts/jquery/jquery-ui.min-1.9.2/css/custom/jquery-ui-1.9.2.custom.min.css', true); + public static function loadJQueryUiLib($viewInstance) + { + self::loadJavascript($viewInstance, 'scripts/jquery/jquery-ui.min-1.9.2/js/jquery-ui-1.9.2.custom.min.js', true); + self::loadStylesheet($viewInstance, 'scripts/jquery/jquery-ui.min-1.9.2/css/custom/jquery-ui-1.9.2.custom.min.css', true); + self::embedStylesheet($viewInstance, '.ui-autocomplete { font-size: 11px; }'); + } - // ui-autocomplete fixup - self::embedStylesheet($viewInstance, ".ui-autocomplete { font-size: 11px; }"); - } + public static function loadChosenLib($viewInstance) + { + self::loadStylesheet($viewInstance, '/modules/Portabilis/Assets/Plugins/Chosen/chosen.css', false); + self::loadJavascript($viewInstance, '/modules/Portabilis/Assets/Plugins/Chosen/chosen.jquery.min.js', false); + } - public static function loadChosenLib($viewInstance) { - self::loadStylesheet($viewInstance, '/modules/Portabilis/Assets/Plugins/Chosen/chosen.css', false); - self::loadJavascript($viewInstance, '/modules/Portabilis/Assets/Plugins/Chosen/chosen.jquery.min.js', false); - } + public static function loadAjaxChosenLib($viewInstance) + { + // AjaxChosen requires this fixup, see https://github.com/meltingice/ajax-chosen + $fixupCss = '.chzn-container .chzn-results .group-result { display: list-item; }'; - public static function loadAjaxChosenLib($viewInstance) { - // AjaxChosen requires this fixup, see https://github.com/meltingice/ajax-chosen - $fixupCss = ".chzn-container .chzn-results .group-result { display: list-item; }"; - Portabilis_View_Helper_Application::embedStylesheet($viewInstance, $fixupCss); + Portabilis_View_Helper_Application::embedStylesheet($viewInstance, $fixupCss); - self::loadJavascript($viewInstance, '/modules/Portabilis/Assets/Plugins/AjaxChosen/ajax-chosen.min.js', false); - } + self::loadJavascript($viewInstance, '/modules/Portabilis/Assets/Plugins/AjaxChosen/ajax-chosen.min.js', false); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Ano.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Ano.php index 7cc7d074be..bfeace030f 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Ano.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Ano.php @@ -2,15 +2,11 @@ require_once 'lib/Portabilis/View/Helper/Input/Ano.php'; - -/* - - Helper DEPRECADO - - #TODO mover referencias de $this->inputsHelper()->dynamic('ano'); - para $this->inputsHelper()->input('ano'); - -*/ - -class Portabilis_View_Helper_DynamicInput_Ano extends Portabilis_View_Helper_Input_Ano { +/** + * Mover referencias de $this->inputsHelper()->dynamic('ano'); para $this->inputsHelper()->input('ano'); + * + * @deprecated + */ +class Portabilis_View_Helper_DynamicInput_Ano extends Portabilis_View_Helper_Input_Ano +{ } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/AnoLetivo.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/AnoLetivo.php index 7a15880f8d..2ebde1d63f 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/AnoLetivo.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/AnoLetivo.php @@ -1,94 +1,65 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/App/Model/IedFinder.php'; -/** - * Portabilis_View_Helper_DynamicInput_AnoLetivo class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_AnoLetivo extends Portabilis_View_Helper_DynamicInput_CoreSelect { +class Portabilis_View_Helper_DynamicInput_AnoLetivo extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ano_letivo'; + } - // subscreve para não acrescentar '_id' no final - protected function inputName() { - return 'ano_letivo'; - } + protected function filtroSituacao() + { + $tiposSituacao = ['nao_iniciado' => 0, 'em_andamento' => 1, 'finalizado' => 2]; + $situacaoIn = []; - protected function filtroSituacao() { - $tiposSituacao = array('nao_iniciado' => 0, 'em_andamento' => 1, 'finalizado' => 2); - $situacaoIn = array(); + foreach ($tiposSituacao as $nome => $flag) { + if (in_array("$nome", $this->options['situacoes'])) { + $situacaoIn[] = $flag; + } + } - foreach ($tiposSituacao as $nome => $flag) { - if (in_array("$nome", $this->options['situacoes'])) - $situacaoIn[] = $flag; + return (empty($situacaoIn) ? '' : 'and andamento in (' . implode(',', $situacaoIn) . ')'); } - return (empty($situacaoIn) ? '' : 'and andamento in ('. implode(',', $situacaoIn) . ')'); - } + protected function inputOptions($options) + { + $resources = $options['resources']; + $escolaId = $this->getEscolaId($options['escolaId']); + $serieId = $this->getSerieId($options['serieId']); - protected function inputOptions($options) { - $resources = $options['resources']; - $escolaId = $this->getEscolaId($options['escolaId']); - $serieId = $this->getSerieId($options['serieId']); + if ($serieId && $escolaId && empty($resources)) { + $resources = App_Model_IedFinder::getAnosLetivosEscolaSerie($escolaId, $serieId); + } elseif ($escolaId && empty($resources)) { + $sql = " + select ano + from pmieducar.escola_ano_letivo as al + where ref_cod_escola = $1 + and ativo = 1 {$this->filtroSituacao()} + order by ano desc + "; - if ($serieId && $escolaId && empty($resources)) { - $resources = App_Model_IedFinder::getAnosLetivosEscolaSerie($escolaId, $serieId); - //asort($resources); - } else if ($escolaId && empty($resources)) { - $sql = "select ano from pmieducar.escola_ano_letivo as al where ref_cod_escola = $1 - and ativo = 1 {$this->filtroSituacao()} order by ano desc"; + $resources = Portabilis_Utils_Database::fetchPreparedQuery($sql, ['params' => $escolaId]); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'ano', 'ano'); + } - $resources = Portabilis_Utils_Database::fetchPreparedQuery($sql, array('params' => $escolaId)); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'ano', 'ano'); + return $this->insertOption(null, 'Selecione um ano letivo', $resources); } - return $this->insertOption(null, "Selecione um ano letivo", $resources); - } - - protected function defaultOptions() { - return array('escolaId' => null, 'situacoes' => array('em_andamento', 'nao_iniciado', 'finalizado')); - } + protected function defaultOptions() + { + return ['escolaId' => null, 'situacoes' => ['em_andamento', 'nao_iniciado', 'finalizado']]; + } - public function anoLetivo($options = array()) { - parent::select($options); + public function anoLetivo($options = []) + { + parent::select($options); - foreach ($this->options['situacoes'] as $situacao) - $this->viewInstance->appendOutput(""); - } -} \ No newline at end of file + foreach ($this->options['situacoes'] as $situacao) { + $this->viewInstance->appendOutput(""); + } + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/AreaConhecimento.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/AreaConhecimento.php index 92519fa64d..493d8da3da 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/AreaConhecimento.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/AreaConhecimento.php @@ -1,38 +1,23 @@ - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_AreaConhecimento extends Portabilis_View_Helper_DynamicInput_CoreSelect { +class Portabilis_View_Helper_DynamicInput_AreaConhecimento extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'area_conhecimento_id'; + } - protected function inputName() { - return 'area_conhecimento_id'; - } + protected function inputOptions($options) + { + $resources = $options['resources']; - protected function inputOptions($options) { + return $this->insertOption(null, 'Todas', $resources); + } - $resources = $options['resources']; - - // echo "
";var_dump($resources);echo"
"; - // $instituicaoId = $this->getInstituicaoId($options['instituicaoId']); - - // $resources = App_Model_IedFinder::getAreasConhecimento($instituicaoId); - - return $this->insertOption(null, "Todas", $resources); - } - - public function areaConhecimento($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function areaConhecimento($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Biblioteca.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Biblioteca.php index 069394ec8b..7ad09838f2 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Biblioteca.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Biblioteca.php @@ -1,113 +1,79 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; -/** - * Portabilis_View_Helper_DynamicInput_Biblioteca class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Biblioteca extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - protected function inputValue($value = null) { - return $this->getBibliotecaId($value); - } - - - protected function inputName() { - return 'ref_cod_biblioteca'; - } - - - protected function inputOptions($options) { - $resources = $options['resources']; - $instituicaoId = $this->getInstituicaoId(); - $escolaId = $this->getEscolaId(); - - if ($instituicaoId and $escolaId and empty($resources)) { - // se possui id escola então filtra bibliotecas pelo id desta escola - $resources = App_Model_IedFinder::getBibliotecas($instituicaoId, $escolaId); +class Portabilis_View_Helper_DynamicInput_Biblioteca extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputValue($value = null) + { + return $this->getBibliotecaId($value); } - return $this->insertOption(null, "Selecione uma biblioteca", $resources); - } + protected function inputName() + { + return 'ref_cod_biblioteca'; + } + protected function inputOptions($options) + { + $resources = $options['resources']; + $instituicaoId = $this->getInstituicaoId(); + $escolaId = $this->getEscolaId(); - public function selectInput($options = array()) { - parent::select($options); - } + if ($instituicaoId and $escolaId and empty($resources)) { + // se possui id escola então filtra bibliotecas pelo id desta escola + $resources = App_Model_IedFinder::getBibliotecas($instituicaoId, $escolaId); + } + return $this->insertOption(null, 'Selecione uma biblioteca', $resources); + } - public function stringInput($options = array()) { - $defaultOptions = array('options' => array()); - $options = $this->mergeOptions($options, $defaultOptions); + public function selectInput($options = []) + { + parent::select($options); + } - // subescreve $options['options']['value'] com nome escola - if (isset($options['options']['value']) && $options['options']['value']) - $bibliotecaId = $options['options']['value']; - else - $bibliotecaId = $this->getBibliotecaId($options['id']); + public function stringInput($options = []) + { + $defaultOptions = ['options' => []]; + $options = $this->mergeOptions($options, $defaultOptions); - $biblioteca = App_Model_IedFinder::getBiblioteca($bibliotecaId); - $options['options']['value'] = $biblioteca['nm_biblioteca']; + // subescreve $options['options']['value'] com nome escola + if (isset($options['options']['value']) && $options['options']['value']) { + $bibliotecaId = $options['options']['value']; + } else { + $bibliotecaId = $this->getBibliotecaId($options['id']); + } - $defaultInputOptions = array('id' => 'ref_cod_biblioteca', - 'label' => 'Biblioteca', - 'value' => '', - 'inline' => false, - 'descricao' => '', - 'separador' => ':'); + $biblioteca = App_Model_IedFinder::getBiblioteca($bibliotecaId); + $options['options']['value'] = $biblioteca['nm_biblioteca']; - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + $defaultInputOptions = [ + 'id' => 'ref_cod_biblioteca', + 'label' => 'Biblioteca', + 'value' => '', + 'inline' => false, + 'descricao' => '', + 'separador' => ':' + ]; - $this->viewInstance->campoOculto($inputOptions['id'], $bibliotecaId); + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - $inputOptions['id'] = 'biblioteca_nome'; - call_user_func_array(array($this->viewInstance, 'campoRotulo'), $inputOptions); - } + $this->viewInstance->campoOculto($inputOptions['id'], $bibliotecaId); + $inputOptions['id'] = 'biblioteca_nome'; - public function biblioteca($options = array()) { - if ($this->hasNivelAcesso('POLI_INSTITUCIONAL') || $this->hasNivelAcesso('INSTITUCIONAL')) - $this->selectInput($options); + call_user_func_array([$this->viewInstance, 'campoRotulo'], $inputOptions); + } - elseif($this->hasNivelAcesso('SOMENTE_ESCOLA') || $this->hasNivelAcesso('SOMENTE_BIBLIOTECA')) - $this->stringInput($options); + public function biblioteca($options = []) + { + if ($this->hasNivelAcesso('POLI_INSTITUCIONAL') || $this->hasNivelAcesso('INSTITUCIONAL')) { + $this->selectInput($options); + } elseif ($this->hasNivelAcesso('SOMENTE_ESCOLA') || $this->hasNivelAcesso('SOMENTE_BIBLIOTECA')) { + $this->stringInput($options); + } - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, '/modules/DynamicInput/Assets/Javascripts/Biblioteca.js'); - } + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, '/modules/DynamicInput/Assets/Javascripts/Biblioteca.js'); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaFonte.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaFonte.php index 38dfdf7156..b21f88c8b2 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaFonte.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaFonte.php @@ -1,64 +1,28 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; - -/** - * Portabilis_View_Helper_DynamicInput_BibliotecaFonte class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_BibliotecaFonte extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - protected function inputName() { - return 'ref_cod_fonte'; - } - - protected function inputOptions($options) { - $resources = $options['resources']; - $bibliotecaId = $this->getBibliotecaId(); - - if ($bibliotecaId and empty($resources)) - $resources = App_Model_IedFinder::getBibliotecaFontes($bibliotecaId); - - return $this->insertOption(null, "Selecione uma fonte", $resources); - } - - public function bibliotecaFonte($options = array()) { - parent::select($options); - } +class Portabilis_View_Helper_DynamicInput_BibliotecaFonte extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ref_cod_fonte'; + } + + protected function inputOptions($options) + { + $resources = $options['resources']; + $bibliotecaId = $this->getBibliotecaId(); + + if ($bibliotecaId and empty($resources)) { + $resources = App_Model_IedFinder::getBibliotecaFontes($bibliotecaId); + } + + return $this->insertOption(null, 'Selecione uma fonte', $resources); + } + + public function bibliotecaFonte($options = []) + { + parent::select($options); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaCliente.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaCliente.php index b39047679f..d75852d757 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaCliente.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaCliente.php @@ -1,110 +1,75 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/Core.php'; - -/** - * Portabilis_View_Helper_DynamicInput_BibliotecaPesquisaCliente class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_BibliotecaPesquisaCliente extends Portabilis_View_Helper_DynamicInput_Core { - - - protected function getResourceId($id = null) { - if (! $id && $this->viewInstance->ref_cod_cliente) - $id = $this->viewInstance->ref_cod_cliente; - - return $id; - } - - - public function bibliotecaPesquisaCliente($options = array()) { - $defaultOptions = array('id' => null, 'options' => array(), 'hiddenInputOptions' => array()); - $options = $this->mergeOptions($options, $defaultOptions); - - $inputHint = ""; - - // input - $defaultInputOptions = array('id' => 'nome_cliente', - 'label' => 'Cliente', - 'value' => '', - 'size' => '30', - 'max_length' => '255', - 'required' => true, - 'expressao' => false, - 'inline' => false, - 'label_hint' => '', - 'input_hint' => $inputHint, - 'callback' => '', - 'event' => 'onKeyUp', - 'disabled' => true); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - call_user_func_array(array($this->viewInstance, 'campoTexto'), $inputOptions); - - // hidden input - $defaultHiddenInputOptions = array('id' => 'ref_cod_cliente', - 'value' => $this->getResourceId($options['id'])); - - $hiddenInputOptions = $this->mergeOptions($options['hiddenInputOptions'], $defaultHiddenInputOptions); - call_user_func_array(array($this->viewInstance, 'campoOculto'), $hiddenInputOptions); - - // js - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' - var resetCliente = function(){ - $("#ref_cod_cliente").val(""); - $("#nome_cliente").val(""); - } - - $("#ref_cod_biblioteca").change(resetCliente);', true); - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, " - function pesquisaCliente() { - var additionalFields = getElementFor('biblioteca'); - var exceptFields = getElementFor('nome_cliente'); - - if (validatesPresenseOfValueInRequiredFields(additionalFields, exceptFields)) { - var bibliotecaId = getElementFor('biblioteca').val(); - var attrIdName = getElementFor('cliente').attr('id'); - - pesquisa_valores_popless('educar_pesquisa_cliente_lst.php?campo1='+attrIdName+'&campo2=nome_cliente&ref_cod_biblioteca='+bibliotecaId); +class Portabilis_View_Helper_DynamicInput_BibliotecaPesquisaCliente extends Portabilis_View_Helper_DynamicInput_Core +{ + protected function getResourceId($id = null) + { + if (!$id && $this->viewInstance->ref_cod_cliente) { + $id = $this->viewInstance->ref_cod_cliente; } - } - "); - } + + return $id; + } + + public function bibliotecaPesquisaCliente($options = []) + { + $defaultOptions = ['id' => null, 'options' => [], 'hiddenInputOptions' => []]; + $options = $this->mergeOptions($options, $defaultOptions); + + $inputHint = ''; + + $defaultInputOptions = [ + 'id' => 'nome_cliente', + 'label' => 'Cliente', + 'value' => '', + 'size' => '30', + 'max_length' => '255', + 'required' => true, + 'expressao' => false, + 'inline' => false, + 'label_hint' => '', + 'input_hint' => $inputHint, + 'callback' => '', + 'event' => 'onKeyUp', + 'disabled' => true + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + + call_user_func_array([$this->viewInstance, 'campoTexto'], $inputOptions); + + $defaultHiddenInputOptions = [ + 'id' => 'ref_cod_cliente', + 'value' => $this->getResourceId($options['id']) + ]; + + $hiddenInputOptions = $this->mergeOptions($options['hiddenInputOptions'], $defaultHiddenInputOptions); + + call_user_func_array([$this->viewInstance, 'campoOculto'], $hiddenInputOptions); + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' + var resetCliente = function(){ + $("#ref_cod_cliente").val(""); + $("#nome_cliente").val(""); + } + + $("#ref_cod_biblioteca").change(resetCliente); + ', true); + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' + function pesquisaCliente() { + var additionalFields = getElementFor(\'biblioteca\'); + var exceptFields = getElementFor(\'nome_cliente\'); + + if (validatesPresenseOfValueInRequiredFields(additionalFields, exceptFields)) { + var bibliotecaId = getElementFor(\'biblioteca\').val(); + var attrIdName = getElementFor(\'cliente\').attr(\'id\'); + + pesquisa_valores_popless(\'educar_pesquisa_cliente_lst.php?campo1=\'+attrIdName+\'&campo2=nome_cliente&ref_cod_biblioteca=\'+bibliotecaId); + } + } + '); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaObra.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaObra.php index f35d4fc335..e93be4934d 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaObra.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaPesquisaObra.php @@ -1,124 +1,94 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/Core.php'; +class Portabilis_View_Helper_DynamicInput_BibliotecaPesquisaObra extends Portabilis_View_Helper_DynamicInput_Core +{ + protected function getAcervoId($id = null) + { + if (!$id && $this->viewInstance->ref_cod_acervo) { + $id = $this->viewInstance->ref_cod_acervo; + } -/** - * Portabilis_View_Helper_DynamicInput_BibliotecaPesquisaObra class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_BibliotecaPesquisaObra extends Portabilis_View_Helper_DynamicInput_Core { - - protected function getAcervoId($id = null) { - if (! $id && $this->viewInstance->ref_cod_acervo) - $id = $this->viewInstance->ref_cod_acervo; - - return $id; - } - - - protected function getObra($id) { - if (! $id) - $id = $this->getAcervoId($id); - - // chama finder somente se possuir id, senão ocorrerá exception - $obra = empty($id) ? null : App_Model_IedFinder::getBibliotecaObra($this->getBibliotecaId(), $id); - - return $obra; - } - - - public function bibliotecaPesquisaObra($options = array()) { - $defaultOptions = array('id' => null, 'options' => array(), 'hiddenInputOptions' => array()); - $options = $this->mergeOptions($options, $defaultOptions); - - $inputHint = ""; - - // se não recuperar obra, deixa titulo em branco - $obra = $this->getObra($options['id']); - $tituloObra = $obra ? $obra['titulo'] : ''; - - $defaultInputOptions = array('id' => 'titulo_obra', - 'label' => 'Obra', - 'value' => $tituloObra, - 'size' => '30', - 'max_length' => '255', - 'required' => true, - 'expressao' => false, - 'inline' => false, - 'label_hint' => '', - 'input_hint' => $inputHint, - 'callback' => '', - 'event' => 'onKeyUp', - 'disabled' => true); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - call_user_func_array(array($this->viewInstance, 'campoTexto'), $inputOptions); - - // hidden input - $defaultHiddenInputOptions = array('id' => 'ref_cod_acervo', - 'value' => $this->getAcervoId($options['id'])); - - $hiddenInputOptions = $this->mergeOptions($options['hiddenInputOptions'], $defaultHiddenInputOptions); - call_user_func_array(array($this->viewInstance, 'campoOculto'), $hiddenInputOptions); - - // Ao selecionar obra, na pesquisa de obra é setado o value deste elemento - $this->viewInstance->campoOculto("cod_biblioteca", ""); - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' - var resetObra = function(){ - $("#ref_cod_acervo").val(""); - $("#titulo_obra").val(""); - } - - $("#ref_cod_biblioteca").change(resetObra);', true); - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' - function pesquisaObra() { - - var additionalFields = getElementFor("biblioteca"); - var exceptFields = getElementFor("titulo_obra"); - - if (validatesPresenseOfValueInRequiredFields(additionalFields, exceptFields)) { - var bibliotecaId = getElementFor("biblioteca").val(); + return $id; + } - pesquisa_valores_popless("educar_pesquisa_obra_lst.php?campo1=ref_cod_acervo&campo2=titulo_obra&campo3="+bibliotecaId) + protected function getObra($id) + { + if (!$id) { + $id = $this->getAcervoId($id); } - }'); - } -} \ No newline at end of file + + // chama finder somente se possuir id, senão ocorrerá exception + $obra = empty($id) ? null : App_Model_IedFinder::getBibliotecaObra($this->getBibliotecaId(), $id); + + return $obra; + } + + public function bibliotecaPesquisaObra($options = []) + { + $defaultOptions = ['id' => null, 'options' => [], 'hiddenInputOptions' => []]; + $options = $this->mergeOptions($options, $defaultOptions); + + $inputHint = ''; + + // se não recuperar obra, deixa titulo em branco + $obra = $this->getObra($options['id']); + $tituloObra = $obra ? $obra['titulo'] : ''; + + $defaultInputOptions = [ + 'id' => 'titulo_obra', + 'label' => 'Obra', + 'value' => $tituloObra, + 'size' => '30', + 'max_length' => '255', + 'required' => true, + 'expressao' => false, + 'inline' => false, + 'label_hint' => '', + 'input_hint' => $inputHint, + 'callback' => '', + 'event' => 'onKeyUp', + 'disabled' => true + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + + call_user_func_array([$this->viewInstance, 'campoTexto'], $inputOptions); + + $defaultHiddenInputOptions = [ + 'id' => 'ref_cod_acervo', + 'value' => $this->getAcervoId($options['id']) + ]; + + $hiddenInputOptions = $this->mergeOptions($options['hiddenInputOptions'], $defaultHiddenInputOptions); + + call_user_func_array([$this->viewInstance, 'campoOculto'], $hiddenInputOptions); + + // Ao selecionar obra, na pesquisa de obra é setado o value deste elemento + $this->viewInstance->campoOculto('cod_biblioteca', ''); + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' + var resetObra = function(){ + $("#ref_cod_acervo").val(""); + $("#titulo_obra").val(""); + } + + $("#ref_cod_biblioteca").change(resetObra); + ', true); + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' + function pesquisaObra() { + + var additionalFields = getElementFor("biblioteca"); + var exceptFields = getElementFor("titulo_obra"); + + if (validatesPresenseOfValueInRequiredFields(additionalFields, exceptFields)) { + var bibliotecaId = getElementFor("biblioteca").val(); + + pesquisa_valores_popless("educar_pesquisa_obra_lst.php?campo1=ref_cod_acervo&campo2=titulo_obra&campo3="+bibliotecaId) + } + } + '); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaSituacao.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaSituacao.php index 62ea0268de..befe5d4af7 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaSituacao.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaSituacao.php @@ -1,64 +1,28 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; - -/** - * Portabilis_View_Helper_DynamicInput_BibliotecaSituacao class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_BibliotecaSituacao extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - protected function inputName() { - return 'ref_cod_situacao'; - } - - protected function inputOptions($options) { - $resources = $options['resources']; - $bibliotecaId = $this->getBibliotecaId(); - - if ($bibliotecaId and empty($resources)) - $resources = App_Model_IedFinder::getBibliotecaSituacoes($bibliotecaId); - - return $this->insertOption(null, "Selecione uma situação", $resources); - } - - public function bibliotecaSituacao($options = array()) { - parent::select($options); - } -} \ No newline at end of file +class Portabilis_View_Helper_DynamicInput_BibliotecaSituacao extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ref_cod_situacao'; + } + + protected function inputOptions($options) + { + $resources = $options['resources']; + $bibliotecaId = $this->getBibliotecaId(); + + if ($bibliotecaId and empty($resources)) { + $resources = App_Model_IedFinder::getBibliotecaSituacoes($bibliotecaId); + } + + return $this->insertOption(null, 'Selecione uma situação', $resources); + } + + public function bibliotecaSituacao($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoCliente.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoCliente.php index 46feabfbea..fea75b35c8 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoCliente.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoCliente.php @@ -1,68 +1,33 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; - -/** - * Portabilis_View_Helper_DynamicInput_BibliotecaTipoCliente class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_BibliotecaTipoCliente extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - protected function inputName() { - return 'ref_cod_cliente_tipo'; - } - - protected function inputOptions($options) { - $resources = $options['resources']; - $bibliotecaId = $this->getBibliotecaId(); - - if ($bibliotecaId and empty($resources)) - $resources = App_Model_IedFinder::getBibliotecaTiposCliente($bibliotecaId); - - return $this->insertOption(null, "Selecione um tipo de cliente", $resources); - } - - protected function defaultOptions(){ - return array('options' => array('label' => 'Tipo cliente')); - } - - public function bibliotecaTipoCliente($options = array()) { - parent::select($options); - } -} \ No newline at end of file +class Portabilis_View_Helper_DynamicInput_BibliotecaTipoCliente extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ref_cod_cliente_tipo'; + } + + protected function inputOptions($options) + { + $resources = $options['resources']; + $bibliotecaId = $this->getBibliotecaId(); + + if ($bibliotecaId and empty($resources)) { + $resources = App_Model_IedFinder::getBibliotecaTiposCliente($bibliotecaId); + } + + return $this->insertOption(null, 'Selecione um tipo de cliente', $resources); + } + + protected function defaultOptions() + { + return ['options' => ['label' => 'Tipo cliente']]; + } + + public function bibliotecaTipoCliente($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoExemplar.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoExemplar.php index 626a33ed67..2180b8aa12 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoExemplar.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/BibliotecaTipoExemplar.php @@ -1,79 +1,44 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; +class Portabilis_View_Helper_DynamicInput_BibliotecaTipoExemplar extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ref_cod_exemplar_tipo'; + } -/** - * Portabilis_View_Helper_DynamicInput_BibliotecaTipoExemplar class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_BibliotecaTipoExemplar extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - protected function inputName() { - return 'ref_cod_exemplar_tipo'; - } + protected function inputOptions($options) + { + $bibliotecaId = $this->getBibliotecaId($bibliotecaId); + $resources = $options['resources']; - protected function inputOptions($options) { - $bibliotecaId = $this->getBibliotecaId($bibliotecaId); - $resources = $options['resources']; + if (empty($resources) && $bibliotecaId) { + $columns = ['cod_exemplar_tipo', 'nm_tipo']; + $where = ['ref_cod_biblioteca' => $bibliotecaId, 'ativo' => '1']; + $orderBy = ['nm_tipo' => 'ASC']; - if (empty($resources) && $bibliotecaId) { - $columns = array('cod_exemplar_tipo', 'nm_tipo'); - $where = array('ref_cod_biblioteca' => $bibliotecaId, 'ativo' => '1'); - $orderBy = array('nm_tipo' => 'ASC'); + $resources = $this->getDataMapperFor('biblioteca', 'tipoExemplar')->findAll( + $columns, + $where, + $orderBy, + $addColumnIdIfNotSet = false + ); - $resources = $this->getDataMapperFor('biblioteca', 'tipoExemplar')->findAll($columns, - $where, - $orderBy, - $addColumnIdIfNotSet = false); + $resources = Portabilis_Object_Utils::asIdValue($resources, 'cod_exemplar_tipo', 'nm_tipo'); + } - $resources = Portabilis_Object_Utils::asIdValue($resources, 'cod_exemplar_tipo', 'nm_tipo'); + return $this->insertOption(null, 'Selecione um tipo de exemplar', $resources); } - return $this->insertOption(null, "Selecione um tipo de exemplar", $resources); - } - - protected function defaultOptions(){ - return array('options' => array('label' => 'Tipo exemplar')); - } - - public function bibliotecaTipoExemplar($options = array()) { - parent::select($options); - } + protected function defaultOptions() + { + return ['options' => ['label' => 'Tipo exemplar']]; + } -} \ No newline at end of file + public function bibliotecaTipoExemplar($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricular.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricular.php index 3b4df4fd10..eeeb3fc355 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricular.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricular.php @@ -1,82 +1,51 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/Core.php'; - -/** - * Portabilis_View_Helper_DynamicInput_ComponenteCurricular class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_ComponenteCurricular extends Portabilis_View_Helper_DynamicInput_Core { - - protected function getResourceId($id = null) { - if (! $id && $this->viewInstance->ref_cod_componente_curricular) - $id = $this->viewInstance->ref_cod_componente_curricular; - - return $id; - } - - protected function getOptions($turmaId, $resources) { - return $this->insertOption(null, "Selecione um componente curricular", array()); - } - - public function componenteCurricular($options = array()) { - $defaultOptions = array('id' => null, - 'turmaId' => null, - 'options' => array(), - 'resources' => array()); - - $options = $this->mergeOptions($options, $defaultOptions); - $resources = $this->getOptions($options['turmaId'], $options['resources']); - - $defaultSelectOptions = array('id' => 'ref_cod_componente_curricular', - 'label' => 'Componente Curricular', - 'componentes_curriculares' => $resources, - 'value' => $this->getResourceId($options['id']), - 'callback' => '', - 'inline' => false, - 'label_hint' => '', - 'input_hint' => '', - 'disabled' => false, - 'required' => true, - 'multiple' => false); - - $selectOptions = $this->mergeOptions($options['options'], $defaultSelectOptions); - call_user_func_array(array($this->viewInstance, 'campoLista'), $selectOptions); - } +class Portabilis_View_Helper_DynamicInput_ComponenteCurricular extends Portabilis_View_Helper_DynamicInput_Core +{ + protected function getResourceId($id = null) + { + if (!$id && $this->viewInstance->ref_cod_componente_curricular) { + $id = $this->viewInstance->ref_cod_componente_curricular; + } + + return $id; + } + + protected function getOptions($turmaId, $resources) + { + return $this->insertOption(null, 'Selecione um componente curricular', []); + } + + public function componenteCurricular($options = []) + { + $defaultOptions = [ + 'id' => null, + 'turmaId' => null, + 'options' => [], + 'resources' => [] + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + $resources = $this->getOptions($options['turmaId'], $options['resources']); + + $defaultSelectOptions = [ + 'id' => 'ref_cod_componente_curricular', + 'label' => 'Componente Curricular', + 'componentes_curriculares' => $resources, + 'value' => $this->getResourceId($options['id']), + 'callback' => '', + 'inline' => false, + 'label_hint' => '', + 'input_hint' => '', + 'disabled' => false, + 'required' => true, + 'multiple' => false + ]; + + $selectOptions = $this->mergeOptions($options['options'], $defaultSelectOptions); + + call_user_func_array([$this->viewInstance, 'campoLista'], $selectOptions); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricularForDiario.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricularForDiario.php index 1f0cc1cc0c..aacb9fa8cf 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricularForDiario.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricularForDiario.php @@ -1,51 +1,12 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/Core.php'; require_once 'lib/Portabilis/View/Helper/DynamicInput/ComponenteCurricular.php'; -/** - * Portabilis_View_Helper_DynamicInput_ComponenteCurricularForDiario class. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_ComponenteCurricularForDiario extends Portabilis_View_Helper_DynamicInput_ComponenteCurricular { - - public function componenteCurricularForDiario($options = array()){ - return parent::componenteCurricular($options); - } - +class Portabilis_View_Helper_DynamicInput_ComponenteCurricularForDiario extends Portabilis_View_Helper_DynamicInput_ComponenteCurricular +{ + public function componenteCurricularForDiario($options = []) + { + return parent::componenteCurricular($options); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Core.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Core.php index 1121c5aa33..a56eb52b21 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Core.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Core.php @@ -1,52 +1,15 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; -/** - * Portabilis_View_Helper_DynamicInput_Core class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Core extends Portabilis_View_Helper_Input_Core { +class Portabilis_View_Helper_DynamicInput_Core extends Portabilis_View_Helper_Input_Core +{ + protected function loadCoreAssets() + { + parent::loadCoreAssets(); - protected function loadCoreAssets() { - parent::loadCoreAssets(); + $dependencies = ['/modules/DynamicInput/Assets/Javascripts/DynamicInput.js']; - $dependencies = array('/modules/DynamicInput/Assets/Javascripts/DynamicInput.js'); - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $dependencies); - } -} \ No newline at end of file + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $dependencies); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php index abaca578ac..3332f4524a 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php @@ -1,52 +1,15 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/CoreSelect.php'; -/** - * Portabilis_View_Helper_DynamicInput_CoreSelect class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_CoreSelect extends Portabilis_View_Helper_Input_CoreSelect { +class Portabilis_View_Helper_DynamicInput_CoreSelect extends Portabilis_View_Helper_Input_CoreSelect +{ + protected function loadCoreAssets() + { + parent::loadCoreAssets(); - protected function loadCoreAssets() { - parent::loadCoreAssets(); + $dependencies = ['/modules/DynamicInput/Assets/Javascripts/DynamicInput.js']; - $dependencies = array('/modules/DynamicInput/Assets/Javascripts/DynamicInput.js'); - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $dependencies); - } -} \ No newline at end of file + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $dependencies); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/EscolaDestinoTransporteEscolar.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/EscolaDestinoTransporteEscolar.php index 79cab7c0e1..cb623aab52 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/EscolaDestinoTransporteEscolar.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/EscolaDestinoTransporteEscolar.php @@ -2,25 +2,17 @@ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; -/** - * Portabilis_View_Helper_DynamicInput_EscolaDestinoTransporteEscolar class. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_EscolaDestinoTransporteEscolar extends Portabilis_View_Helper_DynamicInput_CoreSelect { +class Portabilis_View_Helper_DynamicInput_EscolaDestinoTransporteEscolar extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; - protected function inputOptions($options) { + return $this->insertOption(null, 'Todos', $resources); + } - $resources = $options['resources']; - return $this->insertOption(null, "Todos", $resources); - } - - public function escolaDestinoTransporteEscolar($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function escolaDestinoTransporteEscolar($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Etapa.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Etapa.php index b09332e836..4684edc538 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Etapa.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Etapa.php @@ -1,60 +1,21 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; +class Portabilis_View_Helper_DynamicInput_Etapa extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'etapa'; + } -/** - * Portabilis_View_Helper_DynamicInput_Etapa class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Etapa extends Portabilis_View_Helper_DynamicInput_CoreSelect { + protected function inputOptions($options) + { + return $this->insertOption(null, 'Selecione uma etapa', $resources); + } - // subscreve para não acrescentar '_id' no final - protected function inputName() { - return 'etapa'; - } - - protected function inputOptions($options) { - // não implementado load resources ainda, por enquanto busca somente com ajax. - return $this->insertOption(null, "Selecione uma etapa", $resources); - } - - public function etapa($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function etapa($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/EtapaEscola.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/EtapaEscola.php index b5376fba76..6738a606cc 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/EtapaEscola.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/EtapaEscola.php @@ -1,69 +1,31 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; - -/** - * Portabilis_View_Helper_DynamicInput_Etapa class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_EtapaEscola extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - // subscreve para não acrescentar '_id' no final - protected function inputName() { - return 'etapa'; - } - - protected function inputOptions($options) { - $resources = $options['resources']; - $instituicaoId = $this->getInstituicaoId($options['instituicaoId'] ?? null); - $escolaId = $this->getEscolaId($options['escolaId'] ?? null); - $ano = $this->viewInstance->ano; - $userId = $this->getCurrentUserId(); - - if ($escolaId && empty($resources)) - $resources = App_Model_IedFinder::getEtapasEscola($ano, $escolaId); - - - return $this->insertOption(null, "Selecione uma etapa", $resources); - } - - public function etapaEscola($options = array()) { - parent::select($options); - } +class Portabilis_View_Helper_DynamicInput_EtapaEscola extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'etapa'; + } + + protected function inputOptions($options) + { + $resources = $options['resources']; + $instituicaoId = $this->getInstituicaoId($options['instituicaoId'] ?? null); + $escolaId = $this->getEscolaId($options['escolaId'] ?? null); + $ano = $this->viewInstance->ano; + $userId = $this->getCurrentUserId(); + + if ($escolaId && empty($resources)) { + $resources = App_Model_IedFinder::getEtapasEscola($ano, $escolaId); + } + + return $this->insertOption(null, 'Selecione uma etapa', $resources); + } + + public function etapaEscola($options = []) + { + parent::select($options); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Instituicao.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Instituicao.php index b6dba8b4d3..8842cddc79 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Instituicao.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Instituicao.php @@ -1,77 +1,42 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; - -/** - * Portabilis_View_Helper_DynamicInput_Instituicao class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Instituicao extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - protected function inputValue($value = null) { - return $this->getInstituicaoId($value); - } - - protected function inputName() { - return 'ref_cod_instituicao'; - } - - protected function inputOptions($options) { - $resources = $options['resources']; - - if (empty($resources)) - $resources = App_Model_IedFinder::getInstituicoes(); - - return $this->insertOption(null, "Selecione uma instituição", $resources); - } - - - protected function defaultOptions(){ - return array('options' => array('label' => 'Instituição')); - } - - - public function selectInput($options = array()) { - parent::select($options); - } - - public function instituicao($options = array()) { - $this->selectInput($options); - } -} \ No newline at end of file +class Portabilis_View_Helper_DynamicInput_Instituicao extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputValue($value = null) + { + return $this->getInstituicaoId($value); + } + + protected function inputName() + { + return 'ref_cod_instituicao'; + } + + protected function inputOptions($options) + { + $resources = $options['resources']; + + if (empty($resources)) { + $resources = App_Model_IedFinder::getInstituicoes(); + } + + return $this->insertOption(null, 'Selecione uma instituição', $resources); + } + + protected function defaultOptions() + { + return ['options' => ['label' => 'Instituição']]; + } + + public function selectInput($options = []) + { + parent::select($options); + } + + public function instituicao($options = []) + { + $this->selectInput($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Matricula.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Matricula.php index 74df224367..81378b8429 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Matricula.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Matricula.php @@ -1,63 +1,26 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; +class Portabilis_View_Helper_DynamicInput_Matricula extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ref_cod_matricula'; + } -/** - * Portabilis_View_Helper_DynamicInput_Matricula class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Matricula extends Portabilis_View_Helper_DynamicInput_CoreSelect { + protected function inputOptions($options) + { + return $this->insertOption(null, 'Selecione uma matrícula', $resources); + } - protected function inputName() { - return 'ref_cod_matricula'; - } + protected function defaultOptions() + { + return ['options' => ['label' => 'Matrícula']]; + } - protected function inputOptions($options) { - // não implementado load resources ainda, por enquanto busca somente com ajax. - return $this->insertOption(null, "Selecione uma matrícula", $resources); - } - - protected function defaultOptions(){ - return array('options' => array('label' => 'Matrícula')); - } - - public function matricula($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function matricula($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/PesquisaAluno.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/PesquisaAluno.php index 7d401f2bdd..e26de0bbed 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/PesquisaAluno.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/PesquisaAluno.php @@ -1,128 +1,96 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/Core.php'; +class Portabilis_View_Helper_DynamicInput_PesquisaAluno extends Portabilis_View_Helper_DynamicInput_Core +{ + protected function inputValue($id = null) + { + if (!$id && $this->viewInstance->ref_cod_aluno) { + $id = $this->viewInstance->ref_cod_aluno; + } -/** - * Portabilis_View_Helper_DynamicInput_PesquisaAluno class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_PesquisaAluno extends Portabilis_View_Helper_DynamicInput_Core { - - protected function inputValue($id = null) { - if (! $id && $this->viewInstance->ref_cod_aluno) - $id = $this->viewInstance->ref_cod_aluno; - - return $id; - } - - - protected function getResource($id) { - if (! $id) - $id = $this->inputValue($id); - - // chama finder somente se possuir id, senão ocorrerá exception - $resource = empty($id) ? null : App_Model_IedFinder::getAluno($this->getEscolaId(), $id); - - return $resource; - } - - - public function pesquisaAluno($options = array()) { - $defaultOptions = array('id' => null, 'options' => array(), 'filterByEscola' => false); - $options = $this->mergeOptions($options, $defaultOptions); - - $inputHint = ""; - - // se não recuperar recurso, deixa resourceLabel em branco - $resource = $this->getResource($options['id']); - $resourceLabel = $resource ? $resource['nome_aluno'] : ''; - - $defaultInputOptions = array('id' => 'nm_aluno', - 'label' => 'Aluno', - 'value' => $resourceLabel, - 'size' => '30', - 'max_length' => '255', - 'required' => true, - 'expressao' => false, - 'inline' => false, - 'label_hint' => '', - 'input_hint' => $inputHint, - 'callback' => '', - 'event' => 'onKeyUp', - 'disabled' => true); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - call_user_func_array(array($this->viewInstance, 'campoTexto'), $inputOptions); - - $this->viewInstance->campoOculto("ref_cod_aluno", $this->inputValue($options['id'])); - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' - var resetAluno = function(){ - $("#ref_cod_aluno").val(""); - $("#nm_aluno").val(""); - } - - $("#ref_cod_escola").change(resetAluno);', true); + return $id; + } - if ($options['filterByEscola']) { - $js = 'function pesquisaAluno() { - var additionalFields = [document.getElementById("ref_cod_escola")]; - var exceptFields = [document.getElementById("nm_aluno")]; + protected function getResource($id) + { + if (!$id) { + $id = $this->inputValue($id); + } - if (validatesPresenseOfValueInRequiredFields(additionalFields, exceptFields)) { + // chama finder somente se possuir id, senão ocorrerá exception + $resource = empty($id) ? null : App_Model_IedFinder::getAluno($this->getEscolaId(), $id); - var escolaId = document.getElementById("ref_cod_escola").value; - pesquisa_valores_popless("/intranet/educar_pesquisa_aluno.php?ref_cod_escola="+escolaId); - } - }'; + return $resource; } - else { - $js = 'function pesquisaAluno() { - var exceptFields = [document.getElementById("nm_aluno")]; - - if (validatesPresenseOfValueInRequiredFields([], exceptFields)) { - pesquisa_valores_popless("/intranet/educar_pesquisa_aluno.php"); - } - }'; + public function pesquisaAluno($options = []) + { + $defaultOptions = ['id' => null, 'options' => [], 'filterByEscola' => false]; + $options = $this->mergeOptions($options, $defaultOptions); + + $inputHint = ''; + + // se não recuperar recurso, deixa resourceLabel em branco + $resource = $this->getResource($options['id']); + $resourceLabel = $resource ? $resource['nome_aluno'] : ''; + + $defaultInputOptions = [ + 'id' => 'nm_aluno', + 'label' => 'Aluno', + 'value' => $resourceLabel, + 'size' => '30', + 'max_length' => '255', + 'required' => true, + 'expressao' => false, + 'inline' => false, + 'label_hint' => '', + 'input_hint' => $inputHint, + 'callback' => '', + 'event' => 'onKeyUp', + 'disabled' => true + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + + call_user_func_array([$this->viewInstance, 'campoTexto'], $inputOptions); + + $this->viewInstance->campoOculto('ref_cod_aluno', $this->inputValue($options['id'])); + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, ' + var resetAluno = function(){ + $("#ref_cod_aluno").val(""); + $("#nm_aluno").val(""); + } + + $("#ref_cod_escola").change(resetAluno); + ', true); + + if ($options['filterByEscola']) { + $js = ' + function pesquisaAluno() { + var additionalFields = [document.getElementById("ref_cod_escola")]; + var exceptFields = [document.getElementById("nm_aluno")]; + + if (validatesPresenseOfValueInRequiredFields(additionalFields, exceptFields)) { + var escolaId = document.getElementById("ref_cod_escola").value; + pesquisa_valores_popless("/intranet/educar_pesquisa_aluno.php?ref_cod_escola="+escolaId); + } + }' + ; + } else { + $js = ' + function pesquisaAluno() { + var exceptFields = [document.getElementById("nm_aluno")]; + + if (validatesPresenseOfValueInRequiredFields([], exceptFields)) { + pesquisa_valores_popless("/intranet/educar_pesquisa_aluno.php"); + } + } + '; + } + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js); } - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js); - } -} \ No newline at end of file +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Rotas.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Rotas.php index 88454277cc..ccf26baea8 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Rotas.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Rotas.php @@ -1,58 +1,23 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Paula Bonot - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; -/** - * Portabilis_View_Helper_DynamicInput_Rotas class. - * - * @author Paula Bonot - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Rotas extends Portabilis_View_Helper_DynamicInput_CoreSelect { +class Portabilis_View_Helper_DynamicInput_Rotas extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ref_cod_rota_transporte_escolar'; + } - protected function inputName() { - return 'ref_cod_rota_transporte_escolar'; - } + protected function inputOptions($options) + { + $resources = $options['resources']; - protected function inputOptions($options) { - $resources = $options['resources']; - return $this->insertOption(null, "Selecione uma rota", $resources); - } + return $this->insertOption(null, 'Selecione uma rota', $resources); + } - public function rotas($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function rotas($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Serie.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Serie.php index 2e0f83d915..4e1c349f55 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Serie.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Serie.php @@ -25,8 +25,8 @@ protected function inputOptions($options) $resources = App_Model_IedFinder::getSeries($instituicaoId = null, $escolaId, $cursoId); } - return $this->insertOption(null, "Selecione uma série", $resources); - } + return $this->insertOption(null, 'Selecione uma série', $resources); + } protected function defaultOptions() { diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Setor.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Setor.php index ac5838d45f..92e96d7dc2 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Setor.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Setor.php @@ -1,64 +1,28 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Matheus Nicoski - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; - -/** - * Portabilis_View_Helper_DynamicInput_Setor class. - * - * @author Matheus Nicoski - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ - -class Portabilis_View_Helper_DynamicInput_Setor extends Portabilis_View_Helper_DynamicInput_CoreSelect { - - protected function inputName() { - return 'id_setor'; - } - - protected function inputOptions($options) { - $resources = $options['resources']; - return $this->insertOption(null, "Selecione um setor", $resources); - } - - protected function defaultOptions(){ - return array('options' => array('label' => 'Setor')); - } - - public function setor($options = array()) { - parent::select($options); - } -} \ No newline at end of file +class Portabilis_View_Helper_DynamicInput_Setor extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'id_setor'; + } + + protected function inputOptions($options) + { + $resources = $options['resources']; + + return $this->insertOption(null, 'Selecione um setor', $resources); + } + + protected function defaultOptions() + { + return ['options' => ['label' => 'Setor']]; + } + + public function setor($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/SituacaoMatricula.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/SituacaoMatricula.php index b2c0774da1..8b40089637 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/SituacaoMatricula.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/SituacaoMatricula.php @@ -1,72 +1,38 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; -/** - * Portabilis_View_Helper_DynamicInput_SituacaoMatricula class. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_SituacaoMatricula extends Portabilis_View_Helper_DynamicInput_CoreSelect { +class Portabilis_View_Helper_DynamicInput_SituacaoMatricula extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; - protected function inputOptions($options) { - $resources = $options['resources']; + $resources = [ + 1 => 'Aprovado', + 2 => 'Reprovado', + 3 => 'Cursando', + 4 => 'Transferido', + 5 => 'Reclassificado', + 6 => 'Abandono', + 9 => 'Exceto Transferidos/Abandono', + 10 => 'Todas', + 12 => 'Aprovado com dependência', + 13 => 'Aprovado pelo conselho', + 14 => 'Reprovado por faltas', + 15 => 'Falecido' + ]; - $resources = array(1 => 'Aprovado', - 2 => 'Reprovado', - 3 => 'Cursando', - 4 => 'Transferido', - 5 => 'Reclassificado', - 6 => 'Abandono', - 9 => 'Exceto Transferidos/Abandono', - 10 => 'Todas', - 12 => 'Aprovado com dependência', - 13 => 'Aprovado pelo conselho', - 14 => 'Reprovado por faltas', - 15 => 'Falecido'); + return $this->insertOption(10, 'Todas', $resources); + } - return $this->insertOption(10, "Todas", $resources); - } + protected function defaultOptions() + { + return ['options' => ['label' => 'Situação']]; + } - protected function defaultOptions(){ - return array('options' => array('label' => 'Situação')); - } - - public function situacaoMatricula($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function situacaoMatricula($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Transferido.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Transferido.php index 3f3c5f0d8e..2b5034cbbc 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Transferido.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Transferido.php @@ -1,63 +1,26 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; +class Portabilis_View_Helper_DynamicInput_Transferido extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputName() + { + return 'ref_cod_matricula'; + } -/** - * Portabilis_View_Helper_DynamicInput_Matricula class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Transferido extends Portabilis_View_Helper_DynamicInput_CoreSelect { + protected function inputOptions($options) + { + return $this->insertOption(null, 'Selecione uma matrícula', $resources); + } - protected function inputName() { - return 'ref_cod_matricula'; - } + protected function defaultOptions() + { + return ['options' => ['label' => 'Matrícula']]; + } - protected function inputOptions($options) { - // não implementado load resources ainda, por enquanto busca somente com ajax. - return $this->insertOption(null, "Selecione uma matrícula", $resources); - } - - protected function defaultOptions(){ - return array('options' => array('label' => 'Matrícula')); - } - - public function transferido($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function transferido($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Vinculo.php b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Vinculo.php index a7d414de98..0dbbd41c8f 100644 --- a/ieducar/lib/Portabilis/View/Helper/DynamicInput/Vinculo.php +++ b/ieducar/lib/Portabilis/View/Helper/DynamicInput/Vinculo.php @@ -1,65 +1,29 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/DynamicInput/CoreSelect.php'; require_once 'lib/Portabilis/Utils/Database.php'; -/** - * Portabilis_View_Helper_DynamicInput_Vinculo class. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_DynamicInput_Vinculo extends Portabilis_View_Helper_DynamicInput_CoreSelect { +class Portabilis_View_Helper_DynamicInput_Vinculo extends Portabilis_View_Helper_DynamicInput_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; - protected function inputOptions($options) { - $resources = $options['resources']; + $sql = 'select cod_funcionario_vinculo, nm_vinculo from portal.funcionario_vinculo'; - $sql = "select cod_funcionario_vinculo, nm_vinculo from portal.funcionario_vinculo"; + $resources = Portabilis_Utils_Database::fetchPreparedQuery($sql); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_funcionario_vinculo', 'nm_vinculo'); - $resources = Portabilis_Utils_Database::fetchPreparedQuery($sql); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_funcionario_vinculo', 'nm_vinculo'); + return $this->insertOption(null, 'Selecione', $resources); + } - return $this->insertOption(null, "Selecione", $resources); - } + protected function defaultOptions() + { + return ['options' => ['label' => 'Vínculo']]; + } - protected function defaultOptions(){ - return array('options' => array('label' => 'Vínculo')); - } - - public function vinculo($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function vinculo($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Checkbox.php b/ieducar/lib/Portabilis/View/Helper/Input/Checkbox.php index c21a986ec0..b4caf834d5 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Checkbox.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Checkbox.php @@ -1,74 +1,37 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; - -/** - * Portabilis_View_Helper_Input_Checkbox class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Checkbox extends Portabilis_View_Helper_Input_Core { - - public function checkbox($attrName, $options = array()) { - $defaultOptions = array('options' => array(), 'objectName' => ''); - $options = $this->mergeOptions($options, $defaultOptions); - - $spacer = ! empty($options['objectName']) && ! empty($attrName) ? '_' : ''; - - $defaultInputOptions = array( - 'id' => $options['objectName'] . $spacer . $attrName, - 'label' => ucwords($attrName), - 'value' => '', - 'label_hint' => '', - 'inline' => false, - 'script' => 'fixupCheckboxValue(this)', - 'disabled' => false - ); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - - // fixup para enviar um valor, junto ao param do checkbox. - $js = "var fixupCheckboxValue = function(input) { - var \$this = \$j(input); - \$this.val(\$this.is(':checked') ? 'on' : ''); - }"; - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); - call_user_func_array(array($this->viewInstance, 'campoCheck'), $inputOptions); - } -} \ No newline at end of file +class Portabilis_View_Helper_Input_Checkbox extends Portabilis_View_Helper_Input_Core +{ + public function checkbox($attrName, $options = []) + { + $defaultOptions = ['options' => [], 'objectName' => '']; + $options = $this->mergeOptions($options, $defaultOptions); + + $spacer = !empty($options['objectName']) && !empty($attrName) ? '_' : ''; + + $defaultInputOptions = [ + 'id' => $options['objectName'] . $spacer . $attrName, + 'label' => ucwords($attrName), + 'value' => '', + 'label_hint' => '', + 'inline' => false, + 'script' => 'fixupCheckboxValue(this)', + 'disabled' => false + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + + // fixup para enviar um valor, junto ao param do checkbox. + $js = ' + var fixupCheckboxValue = function(input) { + var $this = $j(input); + $this.val($this.is(\':checked\') ? \'on\' : \'\'); + } + '; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); + call_user_func_array([$this->viewInstance, 'campoCheck'], $inputOptions); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Core.php b/ieducar/lib/Portabilis/View/Helper/Input/Core.php index 843165c933..c3571fe95c 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Core.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Core.php @@ -12,7 +12,7 @@ class Portabilis_View_Helper_Input_Core { public function __construct($viewInstance, $inputsHelper) { - $this->viewInstance = $viewInstance; + $this->viewInstance = $viewInstance; $this->_inputsHelper = $inputsHelper; $this->loadCoreAssets(); diff --git a/ieducar/lib/Portabilis/View/Helper/Input/CoreSelect.php b/ieducar/lib/Portabilis/View/Helper/Input/CoreSelect.php index dfd5a5481d..74626a166d 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/CoreSelect.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/CoreSelect.php @@ -1,88 +1,64 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; -/** - * Portabilis_View_Helper_DynamicInput_CoreSelect class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_CoreSelect extends Portabilis_View_Helper_Input_Core { +class Portabilis_View_Helper_Input_CoreSelect extends Portabilis_View_Helper_Input_Core +{ + protected function inputName() + { + return parent::inputName() . '_id'; + } - protected function inputName() { - return parent::inputName() . '_id'; - } + public function select($options = []) + { + // this helper options + $defaultOptions = [ + 'id' => null, + 'objectName' => '', + 'attrName' => $this->inputName(), + 'resources' => [], + 'options' => [] + ]; - public function select($options = array()) { - // this helper options - $defaultOptions = array('id' => null, - 'objectName' => '', - 'attrName' => $this->inputName(), - 'resources' => array(), - 'options' => array()); + $defaultOptions = $this->mergeOptions($this->defaultOptions(), $defaultOptions); + $this->options = $this->mergeOptions($options, $defaultOptions); + $this->options['options'] = $this->mergeOptions($this->options['options'], $defaultOptions['options']); - $defaultOptions = $this->mergeOptions($this->defaultOptions(), $defaultOptions); - $this->options = $this->mergeOptions($options, $defaultOptions); - $this->options['options'] = $this->mergeOptions($this->options['options'], $defaultOptions['options']); + // select options - // select options + $defaultInputOptions = [ + 'label' => Portabilis_String_Utils::humanize($this->inputName()), + 'value' => $this->inputValue($this->options['id']), + 'resources' => $this->inputOptions($this->options) + ]; - $defaultInputOptions = array('label' => Portabilis_String_Utils::humanize($this->inputName()), - 'value' => $this->inputValue($this->options['id']), - 'resources' => $this->inputOptions($this->options)); + $inputOptions = $this->mergeOptions($this->options['options'], $defaultInputOptions); + $helperOptions = ['objectName' => $this->options['objectName']]; - $inputOptions = $this->mergeOptions($this->options['options'], $defaultInputOptions); - $helperOptions = array('objectName' => $this->options['objectName']); + // input + $this->inputsHelper()->select($this->options['attrName'], $inputOptions, $helperOptions); + } - // input - $this->inputsHelper()->select($this->options['attrName'], $inputOptions, $helperOptions); - } + /** + * subscrever no child caso deseje carregar mais opções do banco de dados + * antes de carregar a página, ou deixar apenas com a opção padrão e + * carregar via ajax + */ + protected function inputOptions($options) + { + return $this->insertOption( + null, + 'Selecione um(a) ' . Portabilis_String_Utils::humanize($this->inputName()), + $resources + ); + } - // subscrever no child caso deseje carregar mais opções do banco de dados antes de carregar a página, - // ou deixar apenas com a opção padrão e carregar via ajax - protected function inputOptions($options) { - return $this->insertOption(null, - "Selecione um(a) " . Portabilis_String_Utils::humanize($this->inputName()), - $resources); - } - - // overwrite this method in childrens to set additional default options, to be merged with received options, - // and pass to select helper - protected function defaultOptions() { - return array(); - } -} \ No newline at end of file + /** + * overwrite this method in childrens to set additional default options, to + * be merged with received options, and pass to select helper + */ + protected function defaultOptions() + { + return []; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Date.php b/ieducar/lib/Portabilis/View/Helper/Input/Date.php index bc5e2adaa1..dfea3768f9 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Date.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Date.php @@ -1,107 +1,74 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'Portabilis/View/Helper/Input/Core.php'; require_once 'Portabilis/Date/Utils.php'; -/** - * Portabilis_View_Helper_Input_Date class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Date extends Portabilis_View_Helper_Input_Core { - - public function date($attrName, $options = array()) { - $defaultOptions = array('options' => array(), 'objectName' => ''); - - $options = $this->mergeOptions($options, $defaultOptions); - $spacer = ! empty($options['objectName']) && ! empty($attrName) ? '_' : ''; - - $label = ! empty($attrName) ? $attrName : $options['objectName']; - $label = str_replace('_id', '', $label); - - $defaultInputOptions = array('id' => $options['objectName'] . $spacer . $attrName, - 'label' => ucwords($label), - 'value' => null, - 'required' => true, - 'label_hint' => '', - 'inline' => false, - 'callback' => false, - 'disabled' => false, - 'size' => 9, // opção suportada pelo elemento, mas não pelo helper ieducar - 'hint' => 'dd/mm/aaaa', - ); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - - $isDbFormated = strrpos($inputOptions['value'], '-') > -1; - - if ($isDbFormated) - $inputOptions['value'] = Portabilis_Date_Utils::pgSQLToBr($inputOptions['value']); - - call_user_func_array(array($this->viewInstance, 'campoData'), $inputOptions); - $this->fixupPlaceholder($inputOptions); - - // implementado fixup via js, pois algumas opções não estão sendo verificadas pelo helper ieducar. - $this->fixupOptions($inputOptions); - } - - protected function fixupOptions($inputOptions) { - $id = $inputOptions['id']; - - $sizeFixup = "\$input.attr('size', " . $inputOptions['size'] . ");"; - $disableFixup = $inputOptions['disabled'] ? "\$input.attr('disabled', 'disabled');" : ''; - - $script = " - var \$input = \$j('#" . $id . "'); - $sizeFixup - $disableFixup - \$input.change(function(){ - if (this.value == '') { - return true; - } +class Portabilis_View_Helper_Input_Date extends Portabilis_View_Helper_Input_Core +{ + public function date($attrName, $options = []) + { + $defaultOptions = ['options' => [], 'objectName' => '']; + + $options = $this->mergeOptions($options, $defaultOptions); + + $spacer = !empty($options['objectName']) && !empty($attrName) ? '_' : ''; + + $label = !empty($attrName) ? $attrName : $options['objectName']; + $label = str_replace('_id', '', $label); + + $defaultInputOptions = [ + 'id' => $options['objectName'] . $spacer . $attrName, + 'label' => ucwords($label), + 'value' => null, + 'required' => true, + 'label_hint' => '', + 'inline' => false, + 'callback' => false, + 'disabled' => false, + 'size' => 9, // opção suportada pelo elemento, mas não pelo helper ieducar + 'hint' => 'dd/mm/aaaa', + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - var validateData = /^(((0[1-9]|[12][0-9]|3[01])([-.\/])(0[13578]|10|12)([-.\/])(\d{4}))|(([0][1-9]|[12][0-9]|30)([-.\/])(0[469]|11)([-.\/])(\d{4}))|((0[1-9]|1[0-9]|2[0-8])([-.\/])(02)([-.\/])(\d{4}))|((29)(\.|-|\/)(02)([-.\/])([02468][048]00))|((29)([-.\/])(02)([-.\/])([13579][26]00))|((29)([-.\/])(02)([-.\/])([0-9][0-9][0][48]))|((29)([-.\/])(02)([-.\/])([0-9][0-9][2468][048]))|((29)([-.\/])(02)([-.\/])([0-9][0-9][13579][26])))$/; + $isDbFormated = strrpos($inputOptions['value'], '-') > -1; - if (!validateData.test(this.value)){ - messageUtils.error('Informe data válida.', this); - this.value = ''; + if ($isDbFormated) { + $inputOptions['value'] = Portabilis_Date_Utils::pgSQLToBr($inputOptions['value']); } - }); - "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $script, $afterReady = true); - } + call_user_func_array([$this->viewInstance, 'campoData'], $inputOptions); + + $this->fixupPlaceholder($inputOptions); + $this->fixupOptions($inputOptions); + } + + protected function fixupOptions($inputOptions) + { + $id = $inputOptions['id']; + + $sizeFixup = '$input.attr(\'size\', ' . $inputOptions['size'] . ');'; + $disableFixup = $inputOptions['disabled'] ? '$input.attr(\'disabled\', \'disabled\');' : ''; + + $script = ' + var $input = $j(\'#' . $id . "'); + $sizeFixup + $disableFixup + + \$input.change(function(){ + if (this.value == '') { + return true; + } + + var validateData = /^(((0[1-9]|[12][0-9]|3[01])([-.\/])(0[13578]|10|12)([-.\/])(\d{4}))|(([0][1-9]|[12][0-9]|30)([-.\/])(0[469]|11)([-.\/])(\d{4}))|((0[1-9]|1[0-9]|2[0-8])([-.\/])(02)([-.\/])(\d{4}))|((29)(\.|-|\/)(02)([-.\/])([02468][048]00))|((29)([-.\/])(02)([-.\/])([13579][26]00))|((29)([-.\/])(02)([-.\/])([0-9][0-9][0][48]))|((29)([-.\/])(02)([-.\/])([0-9][0-9][2468][048]))|((29)([-.\/])(02)([-.\/])([0-9][0-9][13579][26])))$/; + + if (!validateData.test(this.value)){ + messageUtils.error('Informe data válida.', this); + this.value = ''; + } + }); + "; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $script, $afterReady = true); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Hidden.php b/ieducar/lib/Portabilis/View/Helper/Input/Hidden.php index 7fbad672f3..98cf97ae7f 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Hidden.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Hidden.php @@ -1,59 +1,22 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; +class Portabilis_View_Helper_Input_Hidden extends Portabilis_View_Helper_Input_Core +{ + public function hidden($attrName, $options = []) + { + $defaultOptions = ['options' => [], 'objectName' => '']; + $options = $this->mergeOptions($options, $defaultOptions); + $spacer = !empty($options['objectName']) && !empty($attrName) ? '_' : ''; -/** - * Portabilis_View_Helper_Input_Hidden class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Hidden extends Portabilis_View_Helper_Input_Core { + $defaultInputOptions = [ + 'id' => $options['objectName'] . $spacer . $attrName, + 'value' => '' + ]; - public function hidden($attrName, $options = array()) { - $defaultOptions = array('options' => array(), 'objectName' => ''); - $options = $this->mergeOptions($options, $defaultOptions); - $spacer = ! empty($options['objectName']) && ! empty($attrName) ? '_' : ''; + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - $defaultInputOptions = array('id' => $options['objectName'] . $spacer . $attrName, - 'value' => ''); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - - call_user_func_array(array($this->viewInstance, 'campoOculto'), $inputOptions); - } -} \ No newline at end of file + call_user_func_array([$this->viewInstance, 'campoOculto'], $inputOptions); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Integer.php b/ieducar/lib/Portabilis/View/Helper/Input/Integer.php index 5032046458..78d0ce68e3 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Integer.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Integer.php @@ -1,66 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/View/Helper/Input/Numeric.php'; - -/** - * Portabilis_View_Helper_Input_Integer class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Integer extends Portabilis_View_Helper_Input_Numeric { - - protected function fixupValidation($inputOptions) { - // fixup para remover caracteres não numericos - // inclusive pontos '.', não removidos pela super classe - $js = " \$j('#" . $inputOptions['id'] . "').keyup(function(){ - var oldValue = this.value; - - this.value = this.value.replace(/[^0-9\.]/g, ''); - this.value = this.value.replace('.', ''); - - if (oldValue != this.value) - messageUtils.error('Informe apenas números.', this); - - });"; - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); - } - - public function integer($attrName, $options = array()) { - parent::numeric($attrName, $options); - } +class Portabilis_View_Helper_Input_Integer extends Portabilis_View_Helper_Input_Numeric +{ + protected function fixupValidation($inputOptions) + { + // fixup para remover caracteres não numericos + // inclusive pontos '.', não removidos pela super classe + $js = ' + $j(\'#' . $inputOptions['id'] . "').keyup(function(){ + var oldValue = this.value; + + this.value = this.value.replace(/[^0-9\.]/g, ''); + this.value = this.value.replace('.', ''); + + if (oldValue != this.value) + messageUtils.error('Informe apenas números.', this); + }); + "; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); + } + + public function integer($attrName, $options = []) + { + parent::numeric($attrName, $options); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearch.php b/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearch.php index 44ee77fc71..36ce073dfa 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearch.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearch.php @@ -1,109 +1,57 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; - -/** - * Portabilis_View_Helper_Input_MultipleSearch class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_MultipleSearch extends Portabilis_View_Helper_Input_Core { - - public function multipleSearch($objectName, $attrName, $options = array()) { - $defaultOptions = array('options' => array(), - 'apiModule' => 'Api', - 'apiController' => ucwords($objectName), - 'apiResource' => $objectName . '-search', - 'searchPath' => '', - 'type' => 'multiple'); - - $options = $this->mergeOptions($options, $defaultOptions); - - if (empty($options['searchPath'])) - $options['searchPath'] = "/module/" . $options['apiModule'] . "/" . $options['apiController'] . - "?oper=get&resource=" . $options['apiResource']; - - // #TODO load resources value? - - /* - // load value if received an resource id - $resourceId = $options['hiddenInputOptions']['options']['value']; - - if ($resourceId && ! $options['options']['value']) - $options['options']['value'] = $resourceId . " - ". $this->resourcesValue($resourceId); - */ - - $this->selectInput($objectName, $attrName, $options); - - $this->loadAssets(); - $this->js($objectName, $attrName, $options); - } - - protected function selectInput($objectName, $attrName, $options) { - $textHelperOptions = array('objectName' => $objectName); - - $this->inputsHelper()->select($attrName, $options['options'], $textHelperOptions); - } - - - protected function loadAssets() { - Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); - - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } - - - protected function js($objectName, $attrName, $options) { - // setup multiple search - - /* - all search options (including the option chosenOptions, that is passed for chosen plugin), - can be overwritten adding "var = multipleSearchOptions = { 'options' : 'val', option2 : '_' };" - in the script file for the resource controller. - */ - - $resourceOptions = "multipleSearch" . Portabilis_String_Utils::camelize($objectName) . "Options"; - - $js = "$resourceOptions = typeof $resourceOptions == 'undefined' ? {} : $resourceOptions; - multipleSearchHelper.setup('$objectName', '$attrName', '" . $options['type'] . "','" . $options['type'] . "', $resourceOptions);"; - - // this script will be executed after the script for the current controller (if it was loaded in the view); - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } -} \ No newline at end of file +class Portabilis_View_Helper_Input_MultipleSearch extends Portabilis_View_Helper_Input_Core +{ + public function multipleSearch($objectName, $attrName, $options = []) + { + $defaultOptions = [ + 'options' => [], + 'apiModule' => 'Api', + 'apiController' => ucwords($objectName), + 'apiResource' => $objectName . '-search', + 'searchPath' => '', + 'type' => 'multiple' + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + + if (empty($options['searchPath'])) { + $options['searchPath'] = '/module/' . $options['apiModule'] . '/' . $options['apiController'] . + '?oper=get&resource=' . $options['apiResource']; + } + + $this->selectInput($objectName, $attrName, $options); + + $this->loadAssets(); + $this->js($objectName, $attrName, $options); + } + + protected function selectInput($objectName, $attrName, $options) + { + $textHelperOptions = ['objectName' => $objectName]; + + $this->inputsHelper()->select($attrName, $options['options'], $textHelperOptions); + } + + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); + + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } + + protected function js($objectName, $attrName, $options) + { + $resourceOptions = 'multipleSearch' . Portabilis_String_Utils::camelize($objectName) . 'Options'; + + $js = " + $resourceOptions = typeof $resourceOptions == 'undefined' ? {} : $resourceOptions; + multipleSearchHelper.setup('$objectName', '$attrName', '" . $options['type'] . '\',\'' . $options['type'] . "', $resourceOptions); + "; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearchAjax.php b/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearchAjax.php index a33be0d918..ee828c0675 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearchAjax.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/MultipleSearchAjax.php @@ -1,109 +1,56 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; - -/** - * Portabilis_View_Helper_Input_MultipleSearchAjax class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_MultipleSearchAjax extends Portabilis_View_Helper_Input_Core { - - public function multipleSearchAjax($objectName, $attrName, $options = array()) { - $defaultOptions = array('options' => array(), - 'apiModule' => 'Api', - 'apiController' => ucwords($objectName), - 'apiResource' => $objectName . '-search', - 'searchPath' => ''); - - $options = $this->mergeOptions($options, $defaultOptions); - - if (empty($options['searchPath'])) - $options['searchPath'] = "/module/" . $options['apiModule'] . "/" . $options['apiController'] . - "?oper=get&resource=" . $options['apiResource']; - - // #TODO load resources value? - - /* - // load value if received an resource id - $resourceId = $options['hiddenInputOptions']['options']['value']; - - if ($resourceId && ! $options['options']['value']) - $options['options']['value'] = $resourceId . " - ". $this->resourcesValue($resourceId); - */ - - $this->selectInput($objectName, $attrName, $options); - - $this->loadAssets(); - $this->js($objectName, $attrName, $options); - } - - protected function selectInput($objectName, $attrName, $options) { - $textHelperOptions = array('objectName' => $objectName); - - $this->inputsHelper()->select($attrName, $options['options'], $textHelperOptions); - } - - - protected function loadAssets() { - Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); - Portabilis_View_Helper_Application::loadAjaxChosenLib($this->viewInstance); - - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearchAjax.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } - - - protected function js($objectName, $attrName, $options) { - // setup multiple search - - /* - all search options (including the option ajaxChosenOptions, that is passed for ajaxChosen plugin), - can be overwritten adding "var = multipleSearchAjaxOptions = { 'options' : 'val', option2 : '_' };" - in the script file for the resource controller. - */ - - $resourceOptions = "multipleSearchAjax" . Portabilis_String_Utils::camelize($objectName) . "Options"; - - $js = "$resourceOptions = typeof $resourceOptions == 'undefined' ? {} : $resourceOptions; - multipleSearchAjaxHelper.setup('$objectName', '$attrName', '" . $options['searchPath'] . "', $resourceOptions);"; - - // this script will be executed after the script for the current controller (if it was loaded in the view); - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } -} \ No newline at end of file +class Portabilis_View_Helper_Input_MultipleSearchAjax extends Portabilis_View_Helper_Input_Core +{ + public function multipleSearchAjax($objectName, $attrName, $options = []) + { + $defaultOptions = [ + 'options' => [], + 'apiModule' => 'Api', + 'apiController' => ucwords($objectName), + 'apiResource' => $objectName . '-search', + 'searchPath' => '' + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + + if (empty($options['searchPath'])) { + $options['searchPath'] = '/module/' . $options['apiModule'] . '/' . $options['apiController'] . + '?oper=get&resource=' . $options['apiResource']; + } + + $this->selectInput($objectName, $attrName, $options); + $this->loadAssets(); + $this->js($objectName, $attrName, $options); + } + + protected function selectInput($objectName, $attrName, $options) + { + $textHelperOptions = ['objectName' => $objectName]; + + $this->inputsHelper()->select($attrName, $options['options'], $textHelperOptions); + } + + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); + Portabilis_View_Helper_Application::loadAjaxChosenLib($this->viewInstance); + + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearchAjax.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } + + protected function js($objectName, $attrName, $options) + { + $resourceOptions = 'multipleSearchAjax' . Portabilis_String_Utils::camelize($objectName) . 'Options'; + + $js = " + $resourceOptions = typeof $resourceOptions == 'undefined' ? {} : $resourceOptions; + multipleSearchAjaxHelper.setup('$objectName', '$attrName', '" . $options['searchPath'] . "', $resourceOptions); + "; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Numeric.php b/ieducar/lib/Portabilis/View/Helper/Input/Numeric.php index 63516f4a24..7298e85f2e 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Numeric.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Numeric.php @@ -1,99 +1,63 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; - -/** - * Portabilis_View_Helper_Input_Numeric class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Numeric extends Portabilis_View_Helper_Input_Core { - - protected function fixupValidation($inputOptions) { - // fixup para remover caracteres não numericos - $js = " \$j('#" . $inputOptions['id'] . "').keyup(function(){ - var oldValue = this.value; - this.value = this.value.replace(/[^0-9\.-]/g, ''); - - if (oldValue != this.value) - messageUtils.error('Informe apenas números.', this); - - }); - - \$j('#" . $inputOptions['id'] . "').on('change', function(){ - if (this.value.length && !new RegExp('^-?\\\\d*\\\\.{0,1}\\\\d+$').test(this.value)) { - messageUtils.error('Informe apenas valores numéricos.', this); - this.value = ''; - } - }); - "; - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); - } - - public function numeric($attrName, $options = array()) { - $defaultOptions = array('options' => array(), 'objectName' => ''); - - $options = $this->mergeOptions($options, $defaultOptions); - $spacer = ! empty($options['objectName']) && ! empty($attrName) ? '_' : ''; - - $label = ! empty($attrName) ? $attrName : $options['objectName']; - $label = str_replace('_id', '', $label); - - $defaultInputOptions = array('id' => $options['objectName'] . $spacer . $attrName, - 'label' => ucwords($label), - 'value' => null, - 'size' => 15, - 'max_length' => 15, - 'required' => true, - 'label_hint' => ' ', - 'input_hint' => '', - 'script' => false, - 'event' => 'onKeyUp', - 'inline' => false, - 'disabled' => false); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - $inputOptions['label'] = Portabilis_String_Utils::toLatin1($inputOptions['label'], array('escape' => false)); - - call_user_func_array(array($this->viewInstance, 'campoNumero'), $inputOptions); - - $this->fixupPlaceholder($inputOptions); - $this->fixupValidation($inputOptions); - } +class Portabilis_View_Helper_Input_Numeric extends Portabilis_View_Helper_Input_Core +{ + protected function fixupValidation($inputOptions) + { + // fixup para remover caracteres não numericos + $js = ' + $j(\'#' . $inputOptions['id'] . "').keyup(function(){ + var oldValue = this.value; + this.value = this.value.replace(/[^0-9\.-]/g, ''); + + if (oldValue != this.value) + messageUtils.error('Informe apenas números.', this); + }); + + \$j('#" . $inputOptions['id'] . '\').on(\'change\', function(){ + if (this.value.length && !new RegExp(\'^-?\\\\d*\\\\.{0,1}\\\\d+$\').test(this.value)) { + messageUtils.error(\'Informe apenas valores numéricos.\', this); + this.value = \'\'; + } + }); + '; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); + } + + public function numeric($attrName, $options = []) + { + $defaultOptions = ['options' => [], 'objectName' => '']; + + $options = $this->mergeOptions($options, $defaultOptions); + $spacer = !empty($options['objectName']) && !empty($attrName) ? '_' : ''; + + $label = !empty($attrName) ? $attrName : $options['objectName']; + $label = str_replace('_id', '', $label); + + $defaultInputOptions = [ + 'id' => $options['objectName'] . $spacer . $attrName, + 'label' => ucwords($label), + 'value' => null, + 'size' => 15, + 'max_length' => 15, + 'required' => true, + 'label_hint' => ' ', + 'input_hint' => '', + 'script' => false, + 'event' => 'onKeyUp', + 'inline' => false, + 'disabled' => false + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + $inputOptions['label'] = Portabilis_String_Utils::toLatin1($inputOptions['label'], ['escape' => false]); + + call_user_func_array([$this->viewInstance, 'campoNumero'], $inputOptions); + + $this->fixupPlaceholder($inputOptions); + $this->fixupValidation($inputOptions); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/Beneficio.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/Beneficio.php index b58c6b469e..1af1fcce2b 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/Beneficio.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/Beneficio.php @@ -1,62 +1,24 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/CoreSelect.php'; +class Portabilis_View_Helper_Input_Resource_Beneficio extends Portabilis_View_Helper_Input_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; -/** - * Portabilis_View_Helper_Input_Resource_Beneficio class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_Beneficio extends Portabilis_View_Helper_Input_CoreSelect { + if (empty($resources)) { + $resources = new clsPmieducarAlunoBeneficio(); + $resources = $resources->lista(null, null, null, null, null, null, null, null, null, 1); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_aluno_beneficio', 'nm_beneficio'); + } - protected function inputOptions($options) { - $resources = $options['resources']; - - if (empty($resources)) { - $resources = new clsPmieducarAlunoBeneficio(); - $resources = $resources->lista(null, null, null, null, null, null, null, null, null, 1); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_aluno_beneficio', 'nm_beneficio'); + return $this->insertOption(null, Portabilis_String_Utils::toLatin1('Benefício'), $resources); } - return $this->insertOption(null, Portabilis_String_Utils::toLatin1("Benefício"), $resources); - } - - public function beneficio($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function beneficio($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/EstadoCivil.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/EstadoCivil.php index 75a0a62bb6..6200c46b46 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/EstadoCivil.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/EstadoCivil.php @@ -1,62 +1,24 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/CoreSelect.php'; +class Portabilis_View_Helper_Input_Resource_EstadoCivil extends Portabilis_View_Helper_Input_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; -/** - * Portabilis_View_Helper_Input_Resource_EstadoCivil class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_EstadoCivil extends Portabilis_View_Helper_Input_CoreSelect { + if (empty($resources)) { + $resources = new clsEstadoCivil(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'ideciv', 'descricao'); + } - protected function inputOptions($options) { - $resources = $options['resources']; - - if (empty($resources)) { - $resources = new clsEstadoCivil(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'ideciv', 'descricao'); + return $this->insertOption(null, 'Estado civil', $resources); } - return $this->insertOption(null, "Estado civil", $resources); - } - - public function estadoCivil($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function estadoCivil($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxAreasConhecimento.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxAreasConhecimento.php index 13c8a7feb0..d6ac6864e6 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxAreasConhecimento.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxAreasConhecimento.php @@ -1,77 +1,21 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/View/Helper/Input/MultipleSearchAjax.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchDeficiencias class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ - - -/* - - Classe de modelo para MultipleSearchAjax - - // para usar tal helper, adicionar a view: - - $helperOptions = array('objectName' => 'deficiencias'); - $options = array('label' => 'Deficiencias'); - - $this->inputsHelper()->multipleSearchDeficiencias('', $options, $helperOptions); - - // Esta classe assim com o javascript ainda não está concluida, - // pois o valor não é recuperado para exibição. - -*/ - -class Portabilis_View_Helper_Input_Resource_MultipleSearchAjaxAreasConhecimento extends Portabilis_View_Helper_Input_MultipleSearchAjax { - - public function multipleSearchAjaxAreasConhecimento($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'areasconhecimento', - 'apiController' => 'AreaConhecimentoController', - 'apiResource' => 'areaconhecimento-search'); - - $options = $this->mergeOptions($options, $defaultOptions); - - parent::multipleSearchAjax($options['objectName'], $attrName, $options); - } -} \ No newline at end of file +class Portabilis_View_Helper_Input_Resource_MultipleSearchAjaxAreasConhecimento extends Portabilis_View_Helper_Input_MultipleSearchAjax +{ + public function multipleSearchAjaxAreasConhecimento($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'areasconhecimento', + 'apiController' => 'AreaConhecimentoController', + 'apiResource' => 'areaconhecimento-search' + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + + parent::multipleSearchAjax($options['objectName'], $attrName, $options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxDeficiencias.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxDeficiencias.php index 60fb38e756..735dfbc6fb 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxDeficiencias.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAjaxDeficiencias.php @@ -1,77 +1,21 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - require_once 'lib/Portabilis/View/Helper/Input/MultipleSearchAjax.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchDeficiencias class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ - - -/* - - Classe de modelo para MultipleSearchAjax - - // para usar tal helper, adicionar a view: - - $helperOptions = array('objectName' => 'deficiencias'); - $options = array('label' => 'Deficiencias'); - - $this->inputsHelper()->multipleSearchDeficiencias('', $options, $helperOptions); - - // Esta classe assim com o javascript ainda não está concluida, - // pois o valor não é recuperado para exibição. - -*/ - -class Portabilis_View_Helper_Input_Resource_MultipleSearchAjaxDeficiencias extends Portabilis_View_Helper_Input_MultipleSearchAjax { - - public function multipleSearchDeficiencias($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'deficiencias', - 'apiController' => 'Deficiencia', - 'apiResource' => 'deficiencia-search'); +class Portabilis_View_Helper_Input_Resource_MultipleSearchAjaxDeficiencias extends Portabilis_View_Helper_Input_MultipleSearchAjax +{ + public function multipleSearchDeficiencias($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'deficiencias', + 'apiController' => 'Deficiencia', + 'apiResource' => 'deficiencia-search' + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); - parent::multipleSearchAjax($options['objectName'], $attrName, $options); - } + parent::multipleSearchAjax($options['objectName'], $attrName, $options); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAreasConhecimento.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAreasConhecimento.php index 06de280ec1..9d31f8341c 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAreasConhecimento.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAreasConhecimento.php @@ -1,80 +1,50 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchEtapacurso class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchAreasConhecimento extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - return $this->insertOption(null, '', $resources); - } - - public function multipleSearchAreasConhecimento($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'areaconhecimento', - 'apiController' => 'AreaConhecimento', - 'apiResource' => 'areaconhecimento-search'); - - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); - - $this->placeholderJs($options); - - parent::multipleSearch($options['objectName'], $attrName, $options); - } - - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione as áreas de conhecimento'); - "; - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } - protected function loadAssets() { - Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchAreaconhecimento.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } -} \ No newline at end of file +class Portabilis_View_Helper_Input_Resource_MultipleSearchAreasConhecimento extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + return $this->insertOption(null, '', $resources); + } + + public function multipleSearchAreasConhecimento($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'areaconhecimento', + 'apiController' => 'AreaConhecimento', + 'apiResource' => 'areaconhecimento-search' + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); + + $this->placeholderJs($options); + + parent::multipleSearch($options['objectName'], $attrName, $options); + } + + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione as áreas de conhecimento'); + "; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } + + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchAreaconhecimento.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAssuntos.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAssuntos.php index a6717e7f43..136fcb4b90 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAssuntos.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAssuntos.php @@ -1,80 +1,47 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchAssuntos class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchAssuntos extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - if (empty($resources)) { - $resources = new clsPmieducarAcervoAssunto(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_acervo_assunto', 'nm_assunto'); +class Portabilis_View_Helper_Input_Resource_MultipleSearchAssuntos extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + if (empty($resources)) { + $resources = new clsPmieducarAcervoAssunto(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_acervo_assunto', 'nm_assunto'); + } + + return $this->insertOption(null, '', $resources); } - return $this->insertOption(null, '', $resources); - } - - public function multipleSearchAssuntos($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'assuntos', - 'apiController' => 'Assunto', - 'apiResource' => 'assunto-search'); + public function multipleSearchAssuntos($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'assuntos', + 'apiController' => 'Assunto', + 'apiResource' => 'assunto-search' + ]; - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); - //var_dump($options['options']['options']); + $this->placeholderJs($options); - $this->placeholderJs($options); + parent::multipleSearch($options['objectName'], $attrName, $options); + } - parent::multipleSearch($options['objectName'], $attrName, $options); - } + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione os assuntos');"; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione os assuntos'); + "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } -} \ No newline at end of file + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAutores.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAutores.php index e7639d2fd5..799a29b2f4 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAutores.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchAutores.php @@ -1,80 +1,47 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchAutores class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchAutores extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - if (empty($resources)) { - $resources = new clsPmieducarAcervoAutor(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_acervo_autor', 'nm_autor'); +class Portabilis_View_Helper_Input_Resource_MultipleSearchAutores extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + if (empty($resources)) { + $resources = new clsPmieducarAcervoAutor(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_acervo_autor', 'nm_autor'); + } + + return $this->insertOption(null, '', $resources); } - return $this->insertOption(null, '', $resources); - } - - public function multipleSearchAutores($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'autores', - 'apiController' => 'Autor', - 'apiResource' => 'autor-search'); + public function multipleSearchAutores($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'autores', + 'apiController' => 'Autor', + 'apiResource' => 'autor-search' + ]; - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); - //var_dump($options['options']['options']); + $this->placeholderJs($options); - $this->placeholderJs($options); + parent::multipleSearch($options['objectName'], $attrName, $options); + } - parent::multipleSearch($options['objectName'], $attrName, $options); - } + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione os autores');"; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione os autores'); + "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } -} \ No newline at end of file + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchBeneficios.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchBeneficios.php index 1f5dba0b93..40731fec37 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchBeneficios.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchBeneficios.php @@ -1,80 +1,46 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchBeneficios class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchBeneficios extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - if (empty($resources)) { - $resources = new clsPmieducarAlunoBeneficio(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_aluno_beneficio', 'nm_beneficio'); +class Portabilis_View_Helper_Input_Resource_MultipleSearchBeneficios extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + if (empty($resources)) { + $resources = new clsPmieducarAlunoBeneficio(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_aluno_beneficio', 'nm_beneficio'); + } + + return $this->insertOption(null, '', $resources); } - return $this->insertOption(null, '', $resources); - } - - public function multipleSearchBeneficios($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'beneficios', - 'apiController' => 'Beneficio', - 'apiResource' => 'beneficio-search'); - - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); + public function multipleSearchBeneficios($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'beneficios', + 'apiController' => 'Beneficio', + 'apiResource' => 'beneficio-search' + ]; - //var_dump($options['options']['options']); + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); - $this->placeholderJs($options); + $this->placeholderJs($options); - parent::multipleSearch($options['objectName'], $attrName, $options); - } + parent::multipleSearch($options['objectName'], $attrName, $options); + } - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = 'Selecione os benefícios';"; + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = 'Selecione os benefícios'; + "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCategoriaObra.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCategoriaObra.php index 67530c46a7..bda68ab207 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCategoriaObra.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCategoriaObra.php @@ -1,80 +1,47 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchAssuntos class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchCategoriaObra extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - if (empty($resources)) { - $resources = new clsPmieducarCategoriaObra(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'id', 'descricao'); +class Portabilis_View_Helper_Input_Resource_MultipleSearchCategoriaObra extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + if (empty($resources)) { + $resources = new clsPmieducarCategoriaObra(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'id', 'descricao'); + } + + return $this->insertOption(null, '', $resources); } - return $this->insertOption(null, '', $resources); - } - - public function multipleSearchCategoriaObra($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'categorias', - 'apiController' => 'Categoria', - 'apiResource' => 'categoria-search'); + public function multipleSearchCategoriaObra($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'categorias', + 'apiController' => 'Categoria', + 'apiResource' => 'categoria-search' + ]; - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); - //var_dump($options['options']['options']); + $this->placeholderJs($options); - $this->placeholderJs($options); + parent::multipleSearch($options['objectName'], $attrName, $options); + } - parent::multipleSearch($options['objectName'], $attrName, $options); - } + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione as categorias');"; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione as categorias'); + "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } -} \ No newline at end of file + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchComponenteCurricular.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchComponenteCurricular.php index f410294056..548eddaab3 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchComponenteCurricular.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchComponenteCurricular.php @@ -35,9 +35,11 @@ public function multipleSearchComponenteCurricular($attrName, $options = []) protected function placeholderJs($options) { $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; - $searchForArea = $options['searchForArea'] ? "true" : "false"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione os componentes');"; + $searchForArea = $options['searchForArea'] ? 'true' : 'false'; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione os componentes'); + "; $js .= "var searchForArea = {$searchForArea}"; Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCursoAluno.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCursoAluno.php index 8437961ae4..2d7362c4c3 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCursoAluno.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCursoAluno.php @@ -1,78 +1,50 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Maurício Citadini Biléssimo - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchEtapacurso class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchCursoAluno extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - return $this->insertOption(null, '', $resources); - } - - public function multipleSearchCursoAluno($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'cursoaluno', - 'apiController' => 'CursoAluno', - 'apiResource' => 'cursoaluno-search'); - - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); - - $this->placeholderJs($options); - - parent::multipleSearch($options['objectName'], $attrName, $options); - } - - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; $optionsVarName.placeholder = safeUtf8Decode('Selecione os cursos do aluno');"; - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } - protected function loadAssets() { - Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchCursoaluno.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } -} \ No newline at end of file +class Portabilis_View_Helper_Input_Resource_MultipleSearchCursoAluno extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + return $this->insertOption(null, '', $resources); + } + + public function multipleSearchCursoAluno($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'cursoaluno', + 'apiController' => 'CursoAluno', + 'apiResource' => 'cursoaluno-search' + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); + + $this->placeholderJs($options); + + parent::multipleSearch($options['objectName'], $attrName, $options); + } + + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione os cursos do aluno'); + "; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } + + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchCursoaluno.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php index 38200da866..79d2ea48a6 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php @@ -1,81 +1,50 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Paula Bonot - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; require_once 'lib/Utils/SafeJson.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchCustom class. - * - * @author Paula Bonot - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 11/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchCustom extends Portabilis_View_Helper_Input_MultipleSearch { - - public function MultipleSearchCustom($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'custom', - 'apiController' => 'custom', - 'apiResource' => 'custom-search', - 'type' => 'multiple'); - - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->insertOption(NULL, '', $options['options']['options']['all_values']); - - $this->placeholderJs($options); - - parent::multipleSearch($options['objectName'], $attrName, $options); - } - - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione');"; - - $json = SafeJson::encode($options['options']['options']['values']); - - $js .= 'arrayOptions.push({element : $j("#'. $options['objectName'] .'"),values : '. $json .'})'; - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); - } - protected function loadAssets() { - Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchCustom.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } +class Portabilis_View_Helper_Input_Resource_MultipleSearchCustom extends Portabilis_View_Helper_Input_MultipleSearch +{ + public function MultipleSearchCustom($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'custom', + 'apiController' => 'custom', + 'apiResource' => 'custom-search', + 'type' => 'multiple' + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->insertOption(null, '', $options['options']['options']['all_values']); + + $this->placeholderJs($options); + + parent::multipleSearch($options['objectName'], $attrName, $options); + } + + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione'); + "; + + $json = SafeJson::encode($options['options']['options']['values']); + + $js .= 'arrayOptions.push({element : $j("#' . $options['objectName'] . '"),values : ' . $json . '})'; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); + } + + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchCustom.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDeficiencias.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDeficiencias.php index 4a5029c6ef..18fa8f6406 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDeficiencias.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDeficiencias.php @@ -1,90 +1,47 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchDeficiencias class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchDeficiencias extends Portabilis_View_Helper_Input_MultipleSearch { - - /*protected function resourceValue($id) { - if ($id) { - $sql = "select nm_deficiencia from cadastro.deficiencia where cod_deficiencia = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); - } - }*/ - - protected function getOptions($resources) { - if (empty($resources)) { - $resources = new clsCadastroDeficiencia(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_deficiencia', 'nm_deficiencia'); +class Portabilis_View_Helper_Input_Resource_MultipleSearchDeficiencias extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + if (empty($resources)) { + $resources = new clsCadastroDeficiencia(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_deficiencia', 'nm_deficiencia'); + } + + return $this->insertOption(null, '', $resources); } - return $this->insertOption(null, '', $resources); - } + public function multipleSearchDeficiencias($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'deficiencias', + 'apiController' => 'Deficiencia', + 'apiResource' => 'deficiencia-search' + ]; - public function multipleSearchDeficiencias($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'deficiencias', - 'apiController' => 'Deficiencia', - 'apiResource' => 'deficiencia-search'); + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); + $this->placeholderJs($options); - //var_dump($options['options']['options']); - - $this->placeholderJs($options); + parent::multipleSearch($options['objectName'], $attrName, $options); + } - parent::multipleSearch($options['objectName'], $attrName, $options); - } + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = 'Selecione as deficiências';"; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = 'Selecione as deficiências'; + "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDocumentosAtestadoVaga.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDocumentosAtestadoVaga.php index 13d16c4081..bab248f4c4 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDocumentosAtestadoVaga.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchDocumentosAtestadoVaga.php @@ -1,89 +1,57 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; - -/** - * Portabilis_View_Helper_Input_MultipleSearchComponenteCurricular class. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchDocumentosAtestadoVaga extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - - if (empty($resources)) { - $resources = array('certidao_nasci' => 'Certidão de nascimento e/ou carteira de identidade', - 'comprovante_resi' => 'Comprovante de residência', - 'foto_3_4' => 'Foto 3/4', - 'historico_escola' => 'Histórico escolar original', - 'atestado_frequencia' => 'Atestado de frequência original', - 'atestado_transferencia' => 'Atestado de Transferência', - 'decla_vacina' => 'Declaração de vacina da unidade de saúde original', - 'carteira_sus' => 'Carteira do SUS', - 'cartao_bolsa_fami' => 'Cópia do cartão bolsa família', - 'rg_aluno_pai' => 'Cópia do RG (aluno e pai)', - 'cpf_aluno_pai' => 'Cópia do CPF (aluno e pai)', - 'tit_eleitor' => 'Título de eleitor do responsável', - 'doc_nis' => 'Número de Identificação Social - NIS' - ); +class Portabilis_View_Helper_Input_Resource_MultipleSearchDocumentosAtestadoVaga extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + if (empty($resources)) { + $resources = [ + 'certidao_nasci' => 'Certidão de nascimento e/ou carteira de identidade', + 'comprovante_resi' => 'Comprovante de residência', + 'foto_3_4' => 'Foto 3/4', + 'historico_escola' => 'Histórico escolar original', + 'atestado_frequencia' => 'Atestado de frequência original', + 'atestado_transferencia' => 'Atestado de Transferência', + 'decla_vacina' => 'Declaração de vacina da unidade de saúde original', + 'carteira_sus' => 'Carteira do SUS', + 'cartao_bolsa_fami' => 'Cópia do cartão bolsa família', + 'rg_aluno_pai' => 'Cópia do RG (aluno e pai)', + 'cpf_aluno_pai' => 'Cópia do CPF (aluno e pai)', + 'tit_eleitor' => 'Título de eleitor do responsável', + 'doc_nis' => 'Número de Identificação Social - NIS' + ]; + } + + return $this->insertOption(null, '', $resources); } - return $this->insertOption(null, '', $resources); - } - public function multipleSearchDocumentosAtestadoVaga($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'documentos', - 'apiController' => '', - 'apiResource' => ''); + public function multipleSearchDocumentosAtestadoVaga($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'documentos', + 'apiController' => '', + 'apiResource' => '' + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); - $this->placeholderJs($options); + $this->placeholderJs($options); - parent::multipleSearch($options['objectName'], $attrName, $options); - } + parent::multipleSearch($options['objectName'], $attrName, $options); + } - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione os componentes');"; + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione os componentes'); + "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } -} \ No newline at end of file + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEscola.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEscola.php index 2e3cbf61c9..18cc52cf1a 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEscola.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEscola.php @@ -1,83 +1,45 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchEscola class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchEscola extends Portabilis_View_Helper_Input_MultipleSearch { - - protected function getOptions($resources) { - - // if (empty($resources)) { - // $resources = Portabilis_Utils_Database::fetchPreparedQuery('SELECT cod_escola, nome FROM pmieducar.escola INNER JOIN cadastro.pessoa ON (ref_idpes = idpes) WHERE escola.ativo = 1'); - // $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_escola', 'nome'); - // } - - return $this->insertOption(null, '', $resources); - } - - public function multipleSearchEscola($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'escola', 'max_selected_options' => 3); - - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); - - $this->placeholderJs($options); - - parent::multipleSearch($options['objectName'], $attrName, $options); - } - - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione as escolas');"; - - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } - protected function loadAssets() { - Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchEscola.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } -} \ No newline at end of file +class Portabilis_View_Helper_Input_Resource_MultipleSearchEscola extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + return $this->insertOption(null, '', $resources); + } + + public function multipleSearchEscola($attrName, $options = []) + { + $defaultOptions = ['objectName' => 'escola', 'max_selected_options' => 3]; + + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); + + $this->placeholderJs($options); + + parent::multipleSearch($options['objectName'], $attrName, $options); + } + + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione as escolas'); + "; + + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } + + protected function loadAssets() + { + Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchEscola.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEtapacurso.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEtapacurso.php index 72550f85a8..4cd8258e23 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEtapacurso.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchEtapacurso.php @@ -1,77 +1,45 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_MultipleSearchEtapacurso class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_MultipleSearchEtapacurso extends Portabilis_View_Helper_Input_MultipleSearch { +class Portabilis_View_Helper_Input_Resource_MultipleSearchEtapacurso extends Portabilis_View_Helper_Input_MultipleSearch +{ + protected function getOptions($resources) + { + if (empty($resources)) { + $resources = Portabilis_Utils_Database::fetchPreparedQuery('SELECT * FROM modules.etapas_educacenso'); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'id', 'nome'); + } - protected function getOptions($resources) { - if (empty($resources)) { - $resources = Portabilis_Utils_Database::fetchPreparedQuery('SELECT * FROM modules.etapas_educacenso'); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'id', 'nome'); + return $this->insertOption(null, '', $resources); } - return $this->insertOption(null, '', $resources); - } + public function multipleSearchEtapacurso($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'etapacurso', + 'apiController' => 'Etapacurso', + 'apiResource' => 'etapacurso-search' + ]; - public function multipleSearchEtapacurso($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'etapacurso', - 'apiController' => 'Etapacurso', - 'apiResource' => 'etapacurso-search'); + $options = $this->mergeOptions($options, $defaultOptions); + $options['options']['resources'] = $this->getOptions($options['options']['resources']); - $options = $this->mergeOptions($options, $defaultOptions); - $options['options']['resources'] = $this->getOptions($options['options']['resources']); + $this->placeholderJs($options); - $this->placeholderJs($options); - - parent::multipleSearch($options['objectName'], $attrName, $options); - } + parent::multipleSearch($options['objectName'], $attrName, $options); + } - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione as etapas');"; + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione as etapas'); + "; - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } -} \ No newline at end of file + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php index bce072302e..20a875f5b7 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php @@ -7,16 +7,20 @@ class Portabilis_View_Helper_Input_Resource_MultipleSearchSerie extends Portabilis_View_Helper_Input_MultipleSearch { - protected function getOptions($resources) { + protected function getOptions($resources) + { return $this->insertOption(null, '', $resources); } - public function multipleSearchSerie($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'multiple_search_serie', + public function multipleSearchSerie($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'multiple_search_serie', 'apiController' => 'Serie', - 'apiResource' => 'series-curso-grouped'); + 'apiResource' => 'series-curso-grouped' + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); $options['options']['resources'] = $this->getOptions($options['options']['resources']); $this->placeholderJs($options); @@ -24,18 +28,23 @@ public function multipleSearchSerie($attrName, $options = array()) { parent::multipleSearch($options['objectName'], $attrName, $options); } - protected function placeholderJs($options) { - $optionsVarName = "multipleSearch" . Portabilis_String_Utils::camelize($options['objectName']) . "Options"; - $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; - $optionsVarName.placeholder = safeUtf8Decode('Selecione');"; + protected function placeholderJs($options) + { + $optionsVarName = 'multipleSearch' . Portabilis_String_Utils::camelize($options['objectName']) . 'Options'; + $js = " + if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} }; + $optionsVarName.placeholder = safeUtf8Decode('Selecione'); + "; $json = SafeJson::encode($options['options']['values']); - $js .= 'arrayOptions.push({element : $j("#'. $options['objectName'] . "_serie-". $options['options']['coluna'] .'"),values : '. $json .'})'; + $js .= 'arrayOptions.push({element : $j("#' . $options['objectName'] . '_serie-' . $options['options']['coluna'] . '"),values : ' . $json . '})'; Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = false); } - protected function loadAssets() { + + protected function loadAssets() + { Portabilis_View_Helper_Application::loadChosenLib($this->viewInstance); $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/MultipleSearch.js'; Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/Religiao.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/Religiao.php index ebecc01e91..36745bd4ce 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/Religiao.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/Religiao.php @@ -1,64 +1,24 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/CoreSelect.php'; +class Portabilis_View_Helper_Input_Resource_Religiao extends Portabilis_View_Helper_Input_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; -/** - * Portabilis_View_Helper_Input_Resource_Religiao class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ + if (empty($options['resources'])) { + $resources = new clsPmieducarReligiao(); + $resources = $resources->lista(null, null, null, null, null, null, null, null, 1); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_religiao', 'nm_religiao'); + } -class Portabilis_View_Helper_Input_Resource_Religiao extends Portabilis_View_Helper_Input_CoreSelect { - - protected function inputOptions($options) { - $resources = $options['resources']; - - if (empty($options['resources'])) { - $resources = new clsPmieducarReligiao(); - $resources = $resources->lista(null, null, null, null, null, null, null, null, 1); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'cod_religiao', 'nm_religiao'); + return $this->insertOption(null, Portabilis_String_Utils::toLatin1('Religião'), $resources); } - return $this->insertOption(null, Portabilis_String_Utils::toLatin1("Religião"), $resources); - } - - - public function religiao($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function religiao($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAcervo.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAcervo.php index 17becd22fb..019fd83549 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAcervo.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAcervo.php @@ -1,64 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Caroline Salib - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchAcervo class. - * - * @author Caroline Salib - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchAcervo extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchAcervo extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchAcervo($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'acervo', + 'apiController' => 'Acervo', + 'apiResource' => 'acervo-search' + ]; - public function simpleSearchAcervo($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'acervo', - 'apiController' => 'Acervo', - 'apiResource' => 'acervo-search'); + $options = $this->mergeOptions($options, $defaultOptions); - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function inputPlaceholder($inputOptions) + { + return 'Digite um nome para buscar'; + } - protected function inputPlaceholder($inputOptions) { - return 'Digite um nome para buscar'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchAcervo.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchAcervo.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAluno.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAluno.php index 35e50f8490..cfb1587a6b 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAluno.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchAluno.php @@ -1,64 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchAluno class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchAluno extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchAluno extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchAluno($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'aluno', + 'apiController' => 'Aluno', + 'apiResource' => 'aluno-search' + ]; - public function simpleSearchAluno($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'aluno', - 'apiController' => 'Aluno', - 'apiResource' => 'aluno-search'); + $options = $this->mergeOptions($options, $defaultOptions); - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome do aluno'; + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome do aluno'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchAluno.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchAluno.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchBairro.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchBairro.php index f19ae25009..366a8f93b1 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchBairro.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchBairro.php @@ -1,80 +1,46 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchBairro class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchBairro extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchBairro extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchBairro($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'bairro', + 'apiController' => 'Bairro', + 'apiResource' => 'bairro-search', + 'showIdOnValue' => false + ]; + $options = $this->mergeOptions($options, $defaultOptions); - public function simpleSearchBairro($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'bairro', - 'apiController' => 'Bairro', - 'apiResource' => 'bairro-search', - 'showIdOnValue' => false); - - $options = $this->mergeOptions($options, $defaultOptions); - - parent::simpleSearch($options['objectName'], $attrName, $options); - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } - protected function resourceValue($id) { - if ($id) { - $sql = "select nome, zona_localizacao from public.bairro where idbai = $1"; - $options = array('params' => $id, 'return_only' => 'first-row'); - $municipio = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - $nome = $municipio['nome']; - $zona = ($municipio['zona_localizacao'] == 1 ? 'Urbana' : 'Rural'); + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome, zona_localizacao from public.bairro where idbai = $1'; + $options = ['params' => $id, 'return_only' => 'first-row']; + $municipio = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + $nome = $municipio['nome']; + $zona = ($municipio['zona_localizacao'] == 1 ? 'Urbana' : 'Rural'); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]) . " / Zona $zona"; + } + } - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)) . " / Zona $zona"; + protected function inputPlaceholder($inputOptions) + { + return 'Informe o nome do bairro'; } - } - protected function inputPlaceholder($inputOptions) { - return 'Informe o nome do bairro'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchBairro.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } -} \ No newline at end of file + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchBairro.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCartorioInep.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCartorioInep.php index 1fe54e34b6..0661a2c9c0 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCartorioInep.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCartorioInep.php @@ -4,32 +4,34 @@ require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -class Portabilis_View_Helper_Input_Resource_SimpleSearchCartorioInep extends Portabilis_View_Helper_Input_SimpleSearch { - +class Portabilis_View_Helper_Input_Resource_SimpleSearchCartorioInep extends Portabilis_View_Helper_Input_SimpleSearch +{ protected function resourceValue($id) { if ($id) { - $sql = "SELECT id_cartorio || ' - ' || descricao AS nome - FROM cadastro.codigo_cartorio_inep - WHERE id = $1"; + $sql = ' + SELECT id_cartorio || \' - \' || descricao AS nome + FROM cadastro.codigo_cartorio_inep + WHERE id = $1 + '; - $options = array('params' => $id, 'return_only' => 'first-row'); + $options = ['params' => $id, 'return_only' => 'first-row']; $curso_superior = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); $nome = $curso_superior['nome']; - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); } } - public function simpleSearchCartorioInep($attrName, $options = array()) + public function simpleSearchCartorioInep($attrName, $options = []) { - $defaultOptions = array( + $defaultOptions = [ 'objectName' => 'cartorioinep', 'apiController' => 'CartorioInep', - 'apiResource' => 'cartorioinep-search', + 'apiResource' => 'cartorioinep-search', 'showIdOnValue' => false - ); - + ]; + $options = $this->mergeOptions($options, $defaultOptions); parent::simpleSearch($options['objectName'], $attrName, $options); @@ -40,8 +42,9 @@ protected function inputPlaceholder($inputOptions) return 'Informe o código ou nome do cartório'; } - protected function loadAssets() { + protected function loadAssets() + { $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchCartorioInep.js'; Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } -} \ No newline at end of file + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCliente.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCliente.php index dd26c29264..642d2ade1b 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCliente.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCliente.php @@ -1,64 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchCliente class. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchCliente extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchCliente extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchCliente($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'cliente', + 'apiController' => 'Cliente', + 'apiResource' => 'cliente-search' + ]; - public function simpleSearchCliente($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'cliente', - 'apiController' => 'Cliente', - 'apiResource' => 'cliente-search'); + $options = $this->mergeOptions($options, $defaultOptions); - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function inputPlaceholder($inputOptions) + { + return 'Digite um nome para buscar'; + } - protected function inputPlaceholder($inputOptions) { - return 'Digite um nome para buscar'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchCliente.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchCliente.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCursoSuperior.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCursoSuperior.php index 11722136f9..3889259949 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCursoSuperior.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchCursoSuperior.php @@ -1,78 +1,51 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchCursoSuperior class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchCursoSuperior extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select curso_id || ' - ' || nome || ' / ' || coalesce((case grau_academico - when 1 then 'Tecnológico' - when 2 then 'Licenciatura' - when 3 then 'Bacharelado' end), '') as nome - from modules.educacenso_curso_superior where id = $1"; - - $options = array('params' => $id, 'return_only' => 'first-row'); - $curso_superior = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - $nome = $curso_superior['nome']; - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchCursoSuperior extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = ' + select curso_id || \' - \' || nome || \' / \' || coalesce( + ( + case grau_academico + when 1 then \'Tecnológico\' + when 2 then \'Licenciatura\' + when 3 then \'Bacharelado\' + end + ), \'\') as nome + from modules.educacenso_curso_superior + where id = $1 + '; + + $options = ['params' => $id, 'return_only' => 'first-row']; + $curso_superior = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + $nome = $curso_superior['nome']; + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - public function simpleSearchCursoSuperior($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'cursosuperior', - 'apiController' => 'CursoSuperior', - 'apiResource' => 'cursosuperior-search', - 'showIdOnValue' => false); + public function simpleSearchCursoSuperior($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'cursosuperior', + 'apiController' => 'CursoSuperior', + 'apiResource' => 'cursosuperior-search', + 'showIdOnValue' => false + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); - parent::simpleSearch($options['objectName'], $attrName, $options); - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome do curso'; - } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome do curso'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchDistrito.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchDistrito.php index f197f63716..15aacc7592 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchDistrito.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchDistrito.php @@ -1,78 +1,44 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchDistrito class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchDistrito extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchDistrito extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchDistrito($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'distrito', + 'apiController' => 'Distrito', + 'apiResource' => 'distrito-search', + 'showIdOnValue' => false + ]; + $options = $this->mergeOptions($options, $defaultOptions); - public function simpleSearchDistrito($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'distrito', - 'apiController' => 'Distrito', - 'apiResource' => 'distrito-search', - 'showIdOnValue' => false); - - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome from public.distrito where iddis = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $distrito = $id . ' - ' . Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - protected function resourceValue($id) { - if ($id) { - $sql = "select nome from public.distrito where iddis = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $distrito = $id. ' - '. Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + return Portabilis_String_Utils::toLatin1($distrito, ['transform' => true, 'escape' => false]); + } + } - return Portabilis_String_Utils::toLatin1($distrito, array('transform' => true, 'escape' => false)); + protected function inputPlaceholder($inputOptions) + { + return 'Informe o nome do distrito'; } - } - protected function inputPlaceholder($inputOptions) { - return 'Informe o nome do distrito'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchDistrito.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } -} \ No newline at end of file + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchDistrito.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEmpresa.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEmpresa.php index 9e32f840d3..53879a707a 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEmpresa.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEmpresa.php @@ -1,70 +1,35 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchEmpresa class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchEmpresa extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select nome from modules.empresa_transporte_escolar, cadastro.pessoa where ref_idpes = idpes and cod_empresa_transporte_escolar = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchEmpresa extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome from modules.empresa_transporte_escolar, cadastro.pessoa where ref_idpes = idpes and cod_empresa_transporte_escolar = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - - public function simpleSearchEmpresa($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'empresa', - 'apiController' => 'Empresa', - 'apiResource' => 'empresa-search'); - $options = $this->mergeOptions($options, $defaultOptions); + public function simpleSearchEmpresa($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'empresa', + 'apiController' => 'Empresa', + 'apiResource' => 'empresa-search' + ]; - parent::simpleSearch($options['objectName'], $attrName, $options); - } + $options = $this->mergeOptions($options, $defaultOptions); - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome da empresa'; - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome da empresa'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEscola.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEscola.php index acdc0c4205..7dba281fd0 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEscola.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchEscola.php @@ -1,64 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchEscola class. - * - * @author Caroline Salib Canto - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchEscola extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchEscola extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchEscola($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'escola', + 'apiController' => 'Escola', + 'apiResource' => 'escola-search' + ]; - public function simpleSearchEscola($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'escola', - 'apiController' => 'Escola', - 'apiResource' => 'escola-search'); + $options = $this->mergeOptions($options, $defaultOptions); - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function inputPlaceholder($inputOptions) + { + return 'Digite um nome para buscar'; + } - protected function inputPlaceholder($inputOptions) { - return 'Digite um nome para buscar'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchEscola.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchEscola.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchIes.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchIes.php index b64b9b7f0a..e067d6219a 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchIes.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchIes.php @@ -1,73 +1,39 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchIes class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchIes extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select ies_id || ' - ' || nome AS nome from modules.educacenso_ies where id = $1"; - $options = array('params' => $id, 'return_only' => 'first-row'); - $ies = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - $nome = $ies['nome']; - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchIes extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select ies_id || \' - \' || nome AS nome from modules.educacenso_ies where id = $1'; + $options = ['params' => $id, 'return_only' => 'first-row']; + $ies = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + $nome = $ies['nome']; + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - public function simpleSearchIes($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'ies', - 'apiController' => 'Ies', - 'apiResource' => 'ies-search', - 'showIdOnValue' => false); + public function simpleSearchIes($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'ies', + 'apiController' => 'Ies', + 'apiResource' => 'ies-search', + 'showIdOnValue' => false + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); - parent::simpleSearch($options['objectName'], $attrName, $options); - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome da instituição'; - } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome da instituição'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchLogradouro.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchLogradouro.php index 7d19ab2094..56e1507c23 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchLogradouro.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchLogradouro.php @@ -1,82 +1,53 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchLogradouro class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchLogradouro extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchLogradouro extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchLogradouro($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'logradouro', + 'apiController' => 'Logradouro', + 'apiResource' => 'logradouro-search', + 'showIdOnValue' => false + ]; + $options = $this->mergeOptions($options, $defaultOptions); - public function simpleSearchLogradouro($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'logradouro', - 'apiController' => 'Logradouro', - 'apiResource' => 'logradouro-search', - 'showIdOnValue' => false); - - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } - - protected function resourceValue($id) { - if ($id) { - $sql = "select nome, descricao as tipo_logradouro from - public.logradouro l left join urbano.tipo_logradouro tl on (l.idtlog = tl.idtlog) - where idlog = $1"; - $options = array('params' => $id, 'return_only' => 'first-row'); - $resource = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - $tipo = Portabilis_String_Utils::toUtf8($resource['tipo_logradouro']); - $nome = Portabilis_String_Utils::toUtf8($resource['nome']); - - return Portabilis_String_Utils::toLatin1($tipo.' '.$nome, array('transform' => true, 'escape' => false)); + protected function resourceValue($id) + { + if ($id) { + $sql = ' + select nome, descricao as tipo_logradouro + from public.logradouro l + left join urbano.tipo_logradouro tl + on (l.idtlog = tl.idtlog) + where idlog = $1 + '; + + $options = ['params' => $id, 'return_only' => 'first-row']; + $resource = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + $tipo = Portabilis_String_Utils::toUtf8($resource['tipo_logradouro']); + $nome = Portabilis_String_Utils::toUtf8($resource['nome']); + + return Portabilis_String_Utils::toLatin1($tipo . ' ' . $nome, ['transform' => true, 'escape' => false]); + } } - } - protected function inputPlaceholder($inputOptions) { - return 'Informe o nome do logradouro'; - } + protected function inputPlaceholder($inputOptions) + { + return 'Informe o nome do logradouro'; + } - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchLogradouro.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } -} \ No newline at end of file + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchLogradouro.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMatricula.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMatricula.php index 37af549960..caed12f33c 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMatricula.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMatricula.php @@ -1,64 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchMatricula class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchMatricula extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchMatricula extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchMatricula($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'matricula', + 'apiController' => 'Matricula', + 'apiResource' => 'matricula-search' + ]; - public function simpleSearchMatricula($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'matricula', - 'apiController' => 'Matricula', - 'apiResource' => 'matricula-search'); + $options = $this->mergeOptions($options, $defaultOptions); - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function inputPlaceholder($inputOptions) + { + return 'Informe o nome do aluno, código ou código da matrícula'; + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o nome do aluno, código ou código da matrícula'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchMatricula.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchMatricula.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMenu.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMenu.php index 3739d3410a..f5b96f30dd 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMenu.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMenu.php @@ -1,66 +1,32 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchMenu class. - * - * @author Gabriel Matos de Souza - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchMenu extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchMenu extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchMenu($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'menu', + 'apiController' => 'Menu', + 'apiResource' => 'menu-search' + ]; - public function simpleSearchMenu($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'menu', - 'apiController' => 'Menu', - 'apiResource' => 'menu-search'); + $options = $this->mergeOptions($options, $defaultOptions); - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function inputPlaceholder($inputOptions) + { + return 'Informe o nome do menu'; + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o nome do menu'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/simpleSearchMenu.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - $style = '/modules/Portabilis/Assets/Stylesheets/Frontend/Inputs/Resource/simpleSearchMenu.css'; - Portabilis_View_Helper_Application::loadStylesheet($this->viewInstance, $style); - } + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/simpleSearchMenu.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + $style = '/modules/Portabilis/Assets/Stylesheets/Frontend/Inputs/Resource/simpleSearchMenu.css'; + Portabilis_View_Helper_Application::loadStylesheet($this->viewInstance, $style); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMotorista.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMotorista.php index 60587fc43f..96f2c608d9 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMotorista.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMotorista.php @@ -1,70 +1,35 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchMotorista class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchMotorista extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select nome from modules.motorista, cadastro.pessoa where ref_idpes = idpes and cod_motorista = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toUtf8($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchMotorista extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome from modules.motorista, cadastro.pessoa where ref_idpes = idpes and cod_motorista = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toUtf8($nome, ['transform' => true, 'escape' => false]); + } } - } - - public function simpleSearchMotorista($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'motorista', - 'apiController' => 'Motorista', - 'apiResource' => 'motorista-search'); - $options = $this->mergeOptions($options, $defaultOptions); + public function simpleSearchMotorista($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'motorista', + 'apiController' => 'Motorista', + 'apiResource' => 'motorista-search' + ]; - parent::simpleSearch($options['objectName'], $attrName, $options); - } + $options = $this->mergeOptions($options, $defaultOptions); - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome do motorista'; - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome do motorista'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMunicipio.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMunicipio.php index 85d39195f9..b2988ff57c 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMunicipio.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchMunicipio.php @@ -1,73 +1,39 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchMunicipio class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchMunicipio extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select nome, sigla_uf from public.municipio where idmun = $1"; - $options = array('params' => $id, 'return_only' => 'first-row'); - $municipio = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - $nome = $municipio['nome']; - $siglaUf = $municipio['sigla_uf']; - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)) . " ($siglaUf)"; +class Portabilis_View_Helper_Input_Resource_SimpleSearchMunicipio extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome, sigla_uf from public.municipio where idmun = $1'; + $options = ['params' => $id, 'return_only' => 'first-row']; + $municipio = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + $nome = $municipio['nome']; + $siglaUf = $municipio['sigla_uf']; + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]) . " ($siglaUf)"; + } } - } - public function simpleSearchMunicipio($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'municipio', - 'apiController' => 'Municipio', - 'apiResource' => 'municipio-search'); + public function simpleSearchMunicipio($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'municipio', + 'apiController' => 'Municipio', + 'apiResource' => 'municipio-search' + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); - parent::simpleSearch($options['objectName'], $attrName, $options); - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome da cidade'; - } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome da cidade'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPais.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPais.php index 1288d137b7..446e118a9a 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPais.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPais.php @@ -1,71 +1,37 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchPais class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchPais extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select nome from public.pais where idpais = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchPais extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome from public.pais where idpais = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - public function simpleSearchPais($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'pais', - 'apiController' => 'Pais', - 'apiResource' => 'pais-search'); + public function simpleSearchPais($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'pais', + 'apiController' => 'Pais', + 'apiResource' => 'pais-search' + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); - parent::simpleSearch($options['objectName'], $attrName, $options); - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome do pais de origem'; - } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome do pais de origem'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoa.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoa.php index 5997f76140..3b0e30982f 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoa.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoa.php @@ -1,86 +1,52 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchPessoa class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchPessoa extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = " - select - (case - when fisica.nome_social not like '' then - fisica.nome_social || ' - Nome de registro: ' || pessoa.nome - else - pessoa.nome - end) as nome - from - cadastro.pessoa, - cadastro.fisica - where true - and pessoa.idpes = $1 - and fisica.idpes = pessoa.idpes - "; - - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchPessoa extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = ' + select + ( + case + when fisica.nome_social not like \'\' then fisica.nome_social || \' - Nome de registro: \' || pessoa.nome + else pessoa.nome + end + ) as nome + from + cadastro.pessoa, + cadastro.fisica + where true + and pessoa.idpes = $1 + and fisica.idpes = pessoa.idpes + '; + + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - public function simpleSearchPessoa($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'pessoa', - 'apiController' => 'Pessoa', - 'apiResource' => 'pessoa-search'); + public function simpleSearchPessoa($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'pessoa', + 'apiController' => 'Pessoa', + 'apiResource' => 'pessoa-search' + ]; - $options = $this->mergeOptions($options, $defaultOptions); + $options = $this->mergeOptions($options, $defaultOptions); - parent::simpleSearch($options['objectName'], $attrName, $options); - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } - protected function inputPlaceholder($inputOptions) { - return 'Informe o nome, código, CPF ou RG da pessoa'; - } + protected function inputPlaceholder($inputOptions) + { + return 'Informe o nome, código, CPF ou RG da pessoa'; + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoaj.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoaj.php index 37867c75fa..950301f5e8 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoaj.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPessoaj.php @@ -1,70 +1,35 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchEmpresa class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchPessoaj extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select nome from cadastro.pessoa where idpes = $1 and tipo='J'"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchPessoaj extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome from cadastro.pessoa where idpes = $1 and tipo=\'J\''; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - - public function simpleSearchPessoaj($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'pessoaj', - 'apiController' => 'Pessoaj', - 'apiResource' => 'pessoaj-search'); - $options = $this->mergeOptions($options, $defaultOptions); + public function simpleSearchPessoaj($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'pessoaj', + 'apiController' => 'Pessoaj', + 'apiResource' => 'pessoaj-search' + ]; - parent::simpleSearch($options['objectName'], $attrName, $options); - } + $options = $this->mergeOptions($options, $defaultOptions); - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou nome da pessoa jurídica'; - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou nome da pessoa jurídica'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPonto.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPonto.php index 59b4176c19..4e58dda202 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPonto.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchPonto.php @@ -1,70 +1,35 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchMotorista class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchPonto extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select descricao from modules.ponto_transporte_escolar where cod_ponto_transporte_escolar = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchPonto extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select descricao from modules.ponto_transporte_escolar where cod_ponto_transporte_escolar = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - - public function simpleSearchPonto($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'ponto', - 'apiController' => 'Ponto', - 'apiResource' => 'ponto-search'); - $options = $this->mergeOptions($options, $defaultOptions); + public function simpleSearchPonto($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'ponto', + 'apiController' => 'Ponto', + 'apiResource' => 'ponto-search' + ]; - parent::simpleSearch($options['objectName'], $attrName, $options); - } + $options = $this->mergeOptions($options, $defaultOptions); - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou a descrição do ponto'; - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou a descrição do ponto'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchProjeto.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchProjeto.php index f8216146cd..42b3db2484 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchProjeto.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchProjeto.php @@ -1,73 +1,38 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão ? - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; require_once 'lib/Portabilis/Utils/Database.php'; require_once 'lib/Portabilis/String/Utils.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchProjeto class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão ? - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchProjeto extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchProjeto extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchProjeto($attrName, $options = []) + { + $defaultOptions = [ + 'objectName' => 'projeto', + 'apiController' => 'Projeto', + 'apiResource' => 'projeto-search', + 'showIdOnValue' => false + ]; + $options = $this->mergeOptions($options, $defaultOptions); - public function simpleSearchProjeto($attrName, $options = array()) { - $defaultOptions = array('objectName' => 'projeto', - 'apiController' => 'Projeto', - 'apiResource' => 'projeto-search', - 'showIdOnValue' => false); - - $options = $this->mergeOptions($options, $defaultOptions); - - parent::simpleSearch($options['objectName'], $attrName, $options); - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } - protected function resourceValue($id) { - if ($id) { - $sql = "select nome from pmieducar.projeto where cod_projeto = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + protected function resourceValue($id) + { + if ($id) { + $sql = 'select nome from pmieducar.projeto where cod_projeto = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - protected function inputPlaceholder($inputOptions) { - return 'Informe o nome do projeto'; - } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o nome do projeto'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRota.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRota.php index 746aa834df..5dd2c48955 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRota.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRota.php @@ -1,70 +1,35 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchMotorista class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchRota extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select descricao from modules.rota_transporte_escolar where cod_rota_transporte_escolar = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchRota extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select descricao from modules.rota_transporte_escolar where cod_rota_transporte_escolar = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - - public function simpleSearchRota($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'rota', - 'apiController' => 'Rota', - 'apiResource' => 'rota-search'); - $options = $this->mergeOptions($options, $defaultOptions); + public function simpleSearchRota($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'rota', + 'apiController' => 'Rota', + 'apiResource' => 'rota-search' + ]; - parent::simpleSearch($options['objectName'], $attrName, $options); - } + $options = $this->mergeOptions($options, $defaultOptions); - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou a descrição da rota'; - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou a descrição da rota'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRotinasAuditoria.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRotinasAuditoria.php index ca30b2b9af..2f913a9f9f 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRotinasAuditoria.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchRotinasAuditoria.php @@ -5,7 +5,8 @@ class Portabilis_View_Helper_Input_Resource_SimpleSearchRotinasAuditoria extends Portabilis_View_Helper_Input_SimpleSearch { - protected function resourceValue($id) { + protected function resourceValue($id) + { return $id; } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchServidor.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchServidor.php index febf6f1457..267b224361 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchServidor.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchServidor.php @@ -1,64 +1,30 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchServidor class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchServidor extends Portabilis_View_Helper_Input_SimpleSearch { +class Portabilis_View_Helper_Input_Resource_SimpleSearchServidor extends Portabilis_View_Helper_Input_SimpleSearch +{ + public function simpleSearchServidor($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'servidor', + 'apiController' => 'Servidor', + 'apiResource' => 'servidor-search' + ]; - public function simpleSearchServidor($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'servidor', - 'apiController' => 'Servidor', - 'apiResource' => 'servidor-search'); + $options = $this->mergeOptions($options, $defaultOptions); - $options = $this->mergeOptions($options, $defaultOptions); + parent::simpleSearch($options['objectName'], $attrName, $options); + } - parent::simpleSearch($options['objectName'], $attrName, $options); - } + protected function inputPlaceholder($inputOptions) + { + return 'Digite um nome para buscar'; + } - protected function inputPlaceholder($inputOptions) { - return 'Digite um nome para buscar'; - } - - protected function loadAssets() { - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchServidor.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - } + protected function loadAssets() + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/SimpleSearchServidor.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchVeiculo.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchVeiculo.php index fdf450ba22..d516d295cf 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchVeiculo.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/SimpleSearchVeiculo.php @@ -1,70 +1,35 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ require_once 'lib/Portabilis/View/Helper/Input/SimpleSearch.php'; -/** - * Portabilis_View_Helper_Input_SimpleSearchMotorista class. - * - * @author Lucas Schmoeller da Silva - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since 07/2013 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Resource_SimpleSearchVeiculo extends Portabilis_View_Helper_Input_SimpleSearch { - - protected function resourceValue($id) { - if ($id) { - $sql = "select (descricao || ',Placa: ' || placa) from modules.veiculo where cod_veiculo = $1"; - $options = array('params' => $id, 'return_only' => 'first-field'); - $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); - - return Portabilis_String_Utils::toLatin1($nome, array('transform' => true, 'escape' => false)); +class Portabilis_View_Helper_Input_Resource_SimpleSearchVeiculo extends Portabilis_View_Helper_Input_SimpleSearch +{ + protected function resourceValue($id) + { + if ($id) { + $sql = 'select (descricao || \',Placa: \' || placa) from modules.veiculo where cod_veiculo = $1'; + $options = ['params' => $id, 'return_only' => 'first-field']; + $nome = Portabilis_Utils_Database::fetchPreparedQuery($sql, $options); + + return Portabilis_String_Utils::toLatin1($nome, ['transform' => true, 'escape' => false]); + } } - } - - public function simpleSearchVeiculo($attrName = '', $options = array()) { - $defaultOptions = array('objectName' => 'veiculo', - 'apiController' => 'Veiculo', - 'apiResource' => 'veiculo-search'); - $options = $this->mergeOptions($options, $defaultOptions); + public function simpleSearchVeiculo($attrName = '', $options = []) + { + $defaultOptions = [ + 'objectName' => 'veiculo', + 'apiController' => 'Veiculo', + 'apiResource' => 'veiculo-search' + ]; - parent::simpleSearch($options['objectName'], $attrName, $options); - } + $options = $this->mergeOptions($options, $defaultOptions); - protected function inputPlaceholder($inputOptions) { - return 'Informe o código ou a descrição do veiculo'; - } + parent::simpleSearch($options['objectName'], $attrName, $options); + } -} \ No newline at end of file + protected function inputPlaceholder($inputOptions) + { + return 'Informe o código ou a descrição do veiculo'; + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/TipoLogradouro.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/TipoLogradouro.php index 8b15d7143c..db3165af02 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/TipoLogradouro.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/TipoLogradouro.php @@ -1,64 +1,24 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/CoreSelect.php'; +class Portabilis_View_Helper_Input_Resource_TipoLogradouro extends Portabilis_View_Helper_Input_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; -/** - * Portabilis_View_Helper_Input_Resource_TipoLogradouro class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ + if (empty($options['resources'])) { + $resources = new clsTipoLogradouro(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'idtlog', 'descricao'); + } -class Portabilis_View_Helper_Input_Resource_TipoLogradouro extends Portabilis_View_Helper_Input_CoreSelect { - - protected function inputOptions($options) { - $resources = $options['resources']; - - if (empty($options['resources'])) { - $resources = new clsTipoLogradouro(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'idtlog', 'descricao'); + return $this->insertOption(null, 'Tipo logradouro', $resources); } - return $this->insertOption(null, "Tipo logradouro", $resources); - } - - - public function tipoLogradouro($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function tipoLogradouro($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/TurmaTurno.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/TurmaTurno.php index f3b1b8a92e..d95c134b67 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/TurmaTurno.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/TurmaTurno.php @@ -1,67 +1,29 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/CoreSelect.php'; +class Portabilis_View_Helper_Input_Resource_TurmaTurno extends Portabilis_View_Helper_Input_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; -/** - * Portabilis_View_Helper_Input_Resource_TurmaTurno class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ + if (empty($options['resources'])) { + $sql = 'select id, nome from pmieducar.turma_turno where ativo = 1 order by id DESC'; + $resources = Portabilis_Utils_Database::fetchPreparedQuery($sql); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'id', 'nome'); + } -class Portabilis_View_Helper_Input_Resource_TurmaTurno extends Portabilis_View_Helper_Input_CoreSelect { - - protected function inputOptions($options) { - $resources = $options['resources']; - - if (empty($options['resources'])) { - $sql = "select id, nome from pmieducar.turma_turno where ativo = 1 order by id DESC"; - $resources = Portabilis_Utils_Database::fetchPreparedQuery($sql); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'id', 'nome'); + return $this->insertOption(null, 'Selecione', $resources); } - return $this->insertOption(null, "Selecione", $resources); - } - - protected function defaultOptions() { - return array('options' => array('label' => 'Turno')); - } + protected function defaultOptions() + { + return ['options' => ['label' => 'Turno']]; + } - public function turmaTurno($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function turmaTurno($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Resource/Uf.php b/ieducar/lib/Portabilis/View/Helper/Input/Resource/Uf.php index 2dfe87e4de..1f1fa07df1 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Resource/Uf.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Resource/Uf.php @@ -1,64 +1,24 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/CoreSelect.php'; +class Portabilis_View_Helper_Input_Resource_Uf extends Portabilis_View_Helper_Input_CoreSelect +{ + protected function inputOptions($options) + { + $resources = $options['resources']; -/** - * Portabilis_View_Helper_Input_Resource_Uf class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ + if (empty($options['resources'])) { + $resources = new clsUf(); + $resources = $resources->lista(); + $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'sigla_uf', 'sigla_uf'); + } -class Portabilis_View_Helper_Input_Resource_Uf extends Portabilis_View_Helper_Input_CoreSelect { - - protected function inputOptions($options) { - $resources = $options['resources']; - - if (empty($options['resources'])) { - $resources = new clsUf(); - $resources = $resources->lista(); - $resources = Portabilis_Array_Utils::setAsIdValue($resources, 'sigla_uf', 'sigla_uf'); + return $this->insertOption(null, 'Estado', $resources); } - return $this->insertOption(null, "Estado", $resources); - } - - - public function uf($options = array()) { - parent::select($options); - } -} \ No newline at end of file + public function uf($options = []) + { + parent::select($options); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Select.php b/ieducar/lib/Portabilis/View/Helper/Input/Select.php index a3328967a2..f1230b55da 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Select.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Select.php @@ -1,69 +1,34 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; +class Portabilis_View_Helper_Input_Select extends Portabilis_View_Helper_Input_Core +{ + public function select($attrName, $options = []) + { + $defaultOptions = ['options' => [], 'objectName' => '', 'resources' => []]; -/** - * Portabilis_View_Helper_Input_Select class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Select extends Portabilis_View_Helper_Input_Core { + $options = $this->mergeOptions($options, $defaultOptions); - public function select($attrName, $options = array()) { - $defaultOptions = array('options' => array(), 'objectName' => '', 'resources' => array()); - $options = $this->mergeOptions($options, $defaultOptions); + $spacer = !empty($options['objectName']) && !empty($attrName) ? '_' : ''; - $spacer = ! empty($options['objectName']) && ! empty($attrName) ? '_' : ''; - $defaultInputOptions = array('id' => $options['objectName'] . $spacer . $attrName, - 'label' => ucwords($attrName), - 'resources' => $options['resources'], - 'value' => '', - 'callback' => '', - 'inline' => false, - 'label_hint' => '', - 'input_hint' => '', - 'disabled' => false, - 'required' => true, - 'multiple' => false); + $defaultInputOptions = [ + 'id' => $options['objectName'] . $spacer . $attrName, + 'label' => ucwords($attrName), + 'resources' => $options['resources'], + 'value' => '', + 'callback' => '', + 'inline' => false, + 'label_hint' => '', + 'input_hint' => '', + 'disabled' => false, + 'required' => true, + 'multiple' => false + ]; - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - $inputOptions['label'] = Portabilis_String_Utils::toLatin1($inputOptions['label'], array('escape' => false)); + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + $inputOptions['label'] = Portabilis_String_Utils::toLatin1($inputOptions['label'], ['escape' => false]); - call_user_func_array(array($this->viewInstance, 'campoLista'), $inputOptions); - } -} \ No newline at end of file + call_user_func_array([$this->viewInstance, 'campoLista'], $inputOptions); + } +} diff --git a/ieducar/lib/Portabilis/View/Helper/Input/SimpleSearch.php b/ieducar/lib/Portabilis/View/Helper/Input/SimpleSearch.php index 024e43b950..798377f9d6 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/SimpleSearch.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/SimpleSearch.php @@ -1,136 +1,93 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; - -/** - * Portabilis_View_Helper_Input_SimpleSearch class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_SimpleSearch extends Portabilis_View_Helper_Input_Core { - - protected function resourceValue($id) { - throw new Exception("You are trying to get the resource value, but this is a generic class, " . - "please, define the method resourceValue in a resource subclass."); - } - - public function simpleSearch($objectName, $attrName, $options = array()) { - $defaultOptions = array('options' => array(), - 'apiModule' => 'Api', - 'apiController' => ucwords($objectName), - 'apiResource' => $objectName . '-search', - 'searchPath' => '', - 'addHiddenInput' => true, - 'hiddenInputOptions' => array(), - 'showIdOnValue' => true); - - $options = $this->mergeOptions($options, $defaultOptions); - - if (empty($options['searchPath'])) - $options['searchPath'] = "/module/" . $options['apiModule'] . "/" . $options['apiController'] . - "?oper=get&resource=" . $options['apiResource']; - - - // load value if received an resource id - $resourceId = $options['hiddenInputOptions']['options']['value']; - - if ($resourceId && ! $options['options']['value']){ - if ($options['showIdOnValue']) - $options['options']['value'] = $resourceId . " - ". $this->resourceValue($resourceId); - else - $options['options']['value'] = $this->resourceValue($resourceId); +class Portabilis_View_Helper_Input_SimpleSearch extends Portabilis_View_Helper_Input_Core +{ + protected function resourceValue($id) + { + throw new Exception( + 'You are trying to get the resource value, but this is a generic class, ' . + 'please, define the method resourceValue in a resource subclass.' + ); } - $this->hiddenInput($objectName, $attrName, $options); - $this->textInput($objectName, $attrName, $options); - $this->js($objectName, $attrName, $options); - } - - - protected function hiddenInput($objectName, $attrName, $options) { - if ($options['addHiddenInput']) { - if ($attrName == 'id') { - throw new CoreExt_Exception("When \$addHiddenInput is true the \$attrName (of the visible input) " . - "must be different than 'id', because the hidden input will use it."); - } - - $defaultHiddenInputOptions = array('options' => array(), 'objectName' => $objectName); - $hiddenInputOptions = $this->mergeOptions($options['hiddenInputOptions'], $defaultHiddenInputOptions); - - $this->inputsHelper()->hidden('id', array(), $hiddenInputOptions); + public function simpleSearch($objectName, $attrName, $options = []) + { + $defaultOptions = [ + 'options' => [], + 'apiModule' => 'Api', + 'apiController' => ucwords($objectName), + 'apiResource' => $objectName . '-search', + 'searchPath' => '', + 'addHiddenInput' => true, + 'hiddenInputOptions' => [], + 'showIdOnValue' => true + ]; + + $options = $this->mergeOptions($options, $defaultOptions); + + if (empty($options['searchPath'])) { + $options['searchPath'] = '/module/' . $options['apiModule'] . '/' . $options['apiController'] . + '?oper=get&resource=' . $options['apiResource']; + } + + $resourceId = $options['hiddenInputOptions']['options']['value']; + + if ($resourceId && !$options['options']['value']) { + if ($options['showIdOnValue']) { + $options['options']['value'] = $resourceId . ' - ' . $this->resourceValue($resourceId); + } else { + $options['options']['value'] = $this->resourceValue($resourceId); + } + } + + $this->hiddenInput($objectName, $attrName, $options); + $this->textInput($objectName, $attrName, $options); + $this->js($objectName, $attrName, $options); } - } - - - protected function textInput($objectName, $attrName, $options) { - $textHelperOptions = array('objectName' => $objectName); - $options['options']['placeholder'] = Portabilis_String_Utils::toLatin1( - $this->inputPlaceholder([]), - array('escape' => false) - ); - - $this->inputsHelper()->text($attrName, $options['options'], $textHelperOptions); - } - - - protected function js($objectName, $attrName, $options) { - // load simple search js - - $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/SimpleSearch.js'; - Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); + protected function hiddenInput($objectName, $attrName, $options) + { + if ($options['addHiddenInput']) { + if ($attrName == 'id') { + throw new CoreExt_Exception( + 'When $addHiddenInput is true the $attrName (of the visible input) ' . + 'must be different than \'id\', because the hidden input will use it.' + ); + } + + $defaultHiddenInputOptions = ['options' => [], 'objectName' => $objectName]; + $hiddenInputOptions = $this->mergeOptions($options['hiddenInputOptions'], $defaultHiddenInputOptions); + + $this->inputsHelper()->hidden('id', [], $hiddenInputOptions); + } + } + protected function textInput($objectName, $attrName, $options) + { + $textHelperOptions = ['objectName' => $objectName]; - // setup simple search + $options['options']['placeholder'] = Portabilis_String_Utils::toLatin1( + $this->inputPlaceholder([]), + ['escape' => false] + ); - /* - all search options (including the option autocompleteOptions, that is passed for jquery autocomplete plugin), - can be overwritten adding "var = simpleSearchOptions = { option : '...', optionName : '...' };" - in the script file for the resource controller. - */ + $this->inputsHelper()->text($attrName, $options['options'], $textHelperOptions); + } - $resourceOptions = "simpleSearch" . Portabilis_String_Utils::camelize($objectName) . "Options"; + protected function js($objectName, $attrName, $options) + { + $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/SimpleSearch.js'; + Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile); - $js = "$resourceOptions = typeof $resourceOptions == 'undefined' ? {} : $resourceOptions; - simpleSearchHelper.setup('$objectName', '$attrName', '" . $options['searchPath'] . "', $resourceOptions);"; + $resourceOptions = 'simpleSearch' . Portabilis_String_Utils::camelize($objectName) . 'Options'; + $js = " + $resourceOptions = typeof $resourceOptions == 'undefined' ? {} : $resourceOptions; + simpleSearchHelper.setup('$objectName', '$attrName', '" . $options['searchPath'] . "', $resourceOptions); + "; - // this script will be executed after the script for the current controller (if it was loaded in the view); - Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); - } + Portabilis_View_Helper_Application::embedJavascript($this->viewInstance, $js, $afterReady = true); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/Text.php b/ieducar/lib/Portabilis/View/Helper/Input/Text.php index 22b32faa2e..891e481665 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/Text.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/Text.php @@ -1,76 +1,39 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; - -/** - * Portabilis_View_Helper_Input_Text class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_Text extends Portabilis_View_Helper_Input_Core { - - public function text($attrName, $options = array()) { - $defaultOptions = array('options' => array(), 'objectName' => ''); - - $options = $this->mergeOptions($options, $defaultOptions); - $spacer = ! empty($options['objectName']) && ! empty($attrName) ? '_' : ''; - - $label = ! empty($attrName) ? $attrName : $options['objectName']; - $label = str_replace('_id', '', $label); - - $defaultInputOptions = array('id' => $options['objectName'] . $spacer . $attrName, - 'label' => ucwords($label), - 'value' => null, - 'size' => 50, - 'max_length' => 50, - 'required' => true, - 'script' => false, - 'inline' => false, - 'label_hint' => '', - 'input_hint' => '', - 'callback' => false, - 'event' => 'onKeyUp', - 'disabled' => false); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - $inputOptions['label'] = Portabilis_String_Utils::toLatin1($inputOptions['label'], array('escape' => false)); - - call_user_func_array(array($this->viewInstance, 'campoTexto'), $inputOptions); - $this->fixupPlaceholder($inputOptions); - } +class Portabilis_View_Helper_Input_Text extends Portabilis_View_Helper_Input_Core +{ + public function text($attrName, $options = []) + { + $defaultOptions = ['options' => [], 'objectName' => '']; + + $options = $this->mergeOptions($options, $defaultOptions); + $spacer = !empty($options['objectName']) && !empty($attrName) ? '_' : ''; + + $label = !empty($attrName) ? $attrName : $options['objectName']; + $label = str_replace('_id', '', $label); + + $defaultInputOptions = [ + 'id' => $options['objectName'] . $spacer . $attrName, + 'label' => ucwords($label), + 'value' => null, + 'size' => 50, + 'max_length' => 50, + 'required' => true, + 'script' => false, + 'inline' => false, + 'label_hint' => '', + 'input_hint' => '', + 'callback' => false, + 'event' => 'onKeyUp', + 'disabled' => false + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + $inputOptions['label'] = Portabilis_String_Utils::toLatin1($inputOptions['label'], ['escape' => false]); + + call_user_func_array([$this->viewInstance, 'campoTexto'], $inputOptions); + $this->fixupPlaceholder($inputOptions); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Input/TextArea.php b/ieducar/lib/Portabilis/View/Helper/Input/TextArea.php index b547a28d4d..6a09256a83 100644 --- a/ieducar/lib/Portabilis/View/Helper/Input/TextArea.php +++ b/ieducar/lib/Portabilis/View/Helper/Input/TextArea.php @@ -1,74 +1,37 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ require_once 'lib/Portabilis/View/Helper/Input/Core.php'; - -/** - * Portabilis_View_Helper_Input_TextArea class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ -class Portabilis_View_Helper_Input_TextArea extends Portabilis_View_Helper_Input_Core { - - public function textArea($attrName, $options = array()) { - $defaultOptions = array('options' => array(), 'objectName' => ''); - - $options = $this->mergeOptions($options, $defaultOptions); - $spacer = ! empty($options['objectName']) && ! empty($attrName) ? '_' : ''; - - $label = ! empty($attrName) ? $attrName : $options['objectName']; - $label = str_replace('_id', '', $label); - - $defaultInputOptions = array('id' => $options['objectName'] . $spacer . $attrName, - 'label' => ucwords($label), - 'value' => null, - 'cols' => 49, - 'rows' => 5, - 'required' => true, - 'label_hint' => '', - 'max_length' => '', - 'inline' => false, - 'script' => false, - 'event' => 'onClick', - 'disabled' => false); - - $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); - - call_user_func_array(array($this->viewInstance, 'campoMemo'), $inputOptions); - $this->fixupPlaceholder($inputOptions); - } +class Portabilis_View_Helper_Input_TextArea extends Portabilis_View_Helper_Input_Core +{ + public function textArea($attrName, $options = []) + { + $defaultOptions = ['options' => [], 'objectName' => '']; + + $options = $this->mergeOptions($options, $defaultOptions); + $spacer = !empty($options['objectName']) && !empty($attrName) ? '_' : ''; + + $label = !empty($attrName) ? $attrName : $options['objectName']; + $label = str_replace('_id', '', $label); + + $defaultInputOptions = [ + 'id' => $options['objectName'] . $spacer . $attrName, + 'label' => ucwords($label), + 'value' => null, + 'cols' => 49, + 'rows' => 5, + 'required' => true, + 'label_hint' => '', + 'max_length' => '', + 'inline' => false, + 'script' => false, + 'event' => 'onClick', + 'disabled' => false + ]; + + $inputOptions = $this->mergeOptions($options['options'], $defaultInputOptions); + + call_user_func_array([$this->viewInstance, 'campoMemo'], $inputOptions); + $this->fixupPlaceholder($inputOptions); + } } diff --git a/ieducar/lib/Portabilis/View/Helper/Inputs.php b/ieducar/lib/Portabilis/View/Helper/Inputs.php index 20a3a52c0e..203b0dff83 100644 --- a/ieducar/lib/Portabilis/View/Helper/Inputs.php +++ b/ieducar/lib/Portabilis/View/Helper/Inputs.php @@ -1,438 +1,397 @@ - * - * Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo - * sob os termos da Licença Pública Geral GNU conforme publicada pela Free - * Software Foundation; tanto a versão 2 da Licença, como (a seu critério) - * qualquer versão posterior. - * - * Este programa é distribuí­do na expectativa de que seja útil, porém, SEM - * NENHUMA GARANTIA; nem mesmo a garantia implí­cita de COMERCIABILIDADE OU - * ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral - * do GNU para mais detalhes. - * - * Você deve ter recebido uma cópia da Licença Pública Geral do GNU junto - * com este programa; se não, escreva para a Free Software Foundation, Inc., no - * endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Arquivo disponível desde a versão 1.1.0 - * @version $Id$ - */ - -/** - * Portabilis_View_Helper_Inputs class. - * - * @author Lucas D'Avila - * @category i-Educar - * @license @@license@@ - * @package Portabilis - * @since Classe disponível desde a versão 1.1.0 - * @version @@package_version@@ - */ - - -class Portabilis_View_Helper_Inputs { - - public function __construct($viewInstance) { - $this->viewInstance = $viewInstance; - } - - - // dynamic inputs helper - /* adiciona inputs de seleção dinamica ao formulário, recebendo diretamente as opcoes do input, - sem necessidade de passar um array com um array de opções, ex: - - Ao invés de: - $this->inputsHelper()->dynamic('instituicao', array('options' => array(required' => false))); - - Pode-se usar: - $this->inputsHelper()->dynamic('instituicao', array(required' => false)); - - Ou - $this->inputsHelper()->dynamic('instituicao', array(), array('options' => array(required' => false))); - - Ou - $this->inputsHelper()->dynamic(array('instituicao', 'escola', 'pesquisaAluno')); - */ - - public function dynamic($helperNames, $inputOptions = array(), $helperOptions = array()) { - $options = $this->mergeInputOptions($inputOptions, $helperOptions); - - if (! is_array($helperNames)) - $helperNames = array($helperNames); - - foreach($helperNames as $helperName) { - $helperClassName = "Portabilis_View_Helper_DynamicInput_" . ucfirst($helperName); - $this->includeHelper($helperClassName); - - $helper = new $helperClassName($this->viewInstance, $this); - $helper->$helperName($options); +class Portabilis_View_Helper_Inputs +{ + public function __construct($viewInstance) + { + $this->viewInstance = $viewInstance; } - } - - // input helpers - - public function input($helperName, $attrName, $inputOptions = array(), $helperOptions = array()) { - $helperClassName = "Portabilis_View_Helper_Input_" . ucfirst($helperName); - - $this->includeHelper($helperClassName); - $helper = new $helperClassName($this->viewInstance, $this); - $helper->$helperName($attrName, $this->mergeInputOptions($inputOptions, $helperOptions)); - } - - public function text($attrNames, $inputOptions = array(), $helperOptions = array()) { - if (! is_array($attrNames)) - $attrNames = array($attrNames); - - foreach($attrNames as $attrName) { - $this->input('text', $attrName, $inputOptions, $helperOptions); + /** + * adiciona inputs de seleção dinamica ao formulário, recebendo diretamente + * as opcoes do input, sem necessidade de passar um array com um array de + * opções, ex: + * + * Ao invés de: + * $this->inputsHelper()->dynamic('instituicao', array('options' => array(required' => false))); + * + * Pode-se usar: + * $this->inputsHelper()->dynamic('instituicao', array(required' => false)); + * + * Ou + * $this->inputsHelper()->dynamic('instituicao', array(), array('options' => array(required' => false))); + * + * Ou + * $this->inputsHelper()->dynamic(array('instituicao', 'escola', 'pesquisaAluno')); + */ + public function dynamic($helperNames, $inputOptions = [], $helperOptions = []) + { + $options = $this->mergeInputOptions($inputOptions, $helperOptions); + + if (!is_array($helperNames)) { + $helperNames = [$helperNames]; + } + + foreach ($helperNames as $helperName) { + $helperClassName = 'Portabilis_View_Helper_DynamicInput_' . ucfirst($helperName); + $this->includeHelper($helperClassName); + + $helper = new $helperClassName($this->viewInstance, $this); + $helper->$helperName($options); + } } - } - - public function numeric($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('numeric', $attrName, $inputOptions, $helperOptions); - } - - public function integer($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('integer', $attrName, $inputOptions, $helperOptions); - } - public function select($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('select', $attrName, $inputOptions, $helperOptions); - } + public function input($helperName, $attrName, $inputOptions = [], $helperOptions = []) + { + $helperClassName = 'Portabilis_View_Helper_Input_' . ucfirst($helperName); - public function search($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('search', $attrName, $inputOptions, $helperOptions); - } - - public function hidden($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('hidden', $attrName, $inputOptions, $helperOptions); - } - - public function checkbox($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('checkbox', $attrName, $inputOptions, $helperOptions); - } - - public function date($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('date', $attrName, $inputOptions, $helperOptions); - } - - public function textArea($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->input('textArea', $attrName, $inputOptions, $helperOptions); - } - - public function booleanSelect($attrName, $inputOptions = array(), $helperOptions = array()) { - $resources = array(); - if (isset($inputOptions['prompt'])) { - $resources[''] = $inputOptions['prompt']; + $this->includeHelper($helperClassName); + $helper = new $helperClassName($this->viewInstance, $this); + $helper->$helperName($attrName, $this->mergeInputOptions($inputOptions, $helperOptions)); } - $resources += array(0 => 'Não', 1 => 'Sim'); - $inputOptions['resources'] = $resources; - $this->select($attrName, $inputOptions, $helperOptions); - } - - - // simple search input helper - - public function simpleSearch($objectName, $attrName, $inputOptions = array(), $helperOptions = array()) { - $options = $this->mergeInputOptions($inputOptions, $helperOptions); - - $helperClassName = 'Portabilis_View_Helper_Input_SimpleSearch'; - $this->includeHelper($helperClassName); - - $helper = new $helperClassName($this->viewInstance, $this); - $helper->simpleSearch($objectName, $attrName, $options); - } - - - // simple search resource input helper - - public function simpleSearchPessoa($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput('simpleSearchPessoa', $attrName, $inputOptions, $helperOptions); - } - - public function simpleSearchPais($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput('simpleSearchPais', $attrName, $inputOptions, $helperOptions); - } - public function simpleSearchMunicipio($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput('simpleSearchMunicipio', $attrName, $inputOptions, $helperOptions); - } + public function text($attrNames, $inputOptions = [], $helperOptions = []) + { + if (!is_array($attrNames)) { + $attrNames = [$attrNames]; + } - public function simpleSearchMatricula($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput('simpleSearchMatricula', $attrName, $inputOptions, $helperOptions); - } - - public function simpleSearchAluno($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput('simpleSearchAluno', $attrName, $inputOptions, $helperOptions); - } - - public function simpleSearchEmpresa($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput('simpleSearchEmpresa', $attrName, $inputOptions, $helperOptions); - } - - public function simpleSearchPessoaj($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput('simpleSearchPessoaj', $attrName, $inputOptions, $helperOptions); - } - - public function simpleSearchMotorista($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchMotorista', $attrName, $inputOptions, $helperOptions); - - } - - public function simpleSearchPonto($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchPonto', $attrName, $inputOptions, $helperOptions); - - } - - public function simpleSearchRota($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchRota', $attrName, $inputOptions, $helperOptions); - - } - - public function simpleSearchVeiculo($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchVeiculo', $attrName, $inputOptions, $helperOptions); - - } - - public function simpleSearchBairro($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchBairro', $attrName, $inputOptions, $helperOptions); - - } - - public function simpleSearchDistrito($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchDistrito', $attrName, $inputOptions, $helperOptions); - - } - - public function simpleSearchLogradouro($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchLogradouro', $attrName, $inputOptions, $helperOptions); - - } - - public function simpleSearchIes($attrName, $inputOptions = array(), $helperOptions = array()) { - - $this->simpleSearchResourceInput('simpleSearchIes', $attrName, $inputOptions, $helperOptions); - - } + foreach ($attrNames as $attrName) { + $this->input('text', $attrName, $inputOptions, $helperOptions); + } + } - public function simpleSearchRotinasAuditoria($attrName, $inputOptions = array(), $helperOptions = array()) { + public function numeric($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('numeric', $attrName, $inputOptions, $helperOptions); + } - $this->simpleSearchResourceInput('simpleSearchRotinasAuditoria', $attrName, $inputOptions, $helperOptions); + public function integer($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('integer', $attrName, $inputOptions, $helperOptions); + } - } + public function select($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('select', $attrName, $inputOptions, $helperOptions); + } - public function simpleSearchCursoSuperior($attrName, $inputOptions = array(), $helperOptions = array()) { + public function search($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('search', $attrName, $inputOptions, $helperOptions); + } - $this->simpleSearchResourceInput('simpleSearchCursoSuperior', $attrName, $inputOptions, $helperOptions); + public function hidden($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('hidden', $attrName, $inputOptions, $helperOptions); + } - } + public function checkbox($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('checkbox', $attrName, $inputOptions, $helperOptions); + } - public function simpleSearchCartorioInep($attrName, $inputOptions = array(), $helperOptions = array()) { + public function date($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('date', $attrName, $inputOptions, $helperOptions); + } - $this->simpleSearchResourceInput('simpleSearchCartorioInep', $attrName, $inputOptions, $helperOptions); + public function textArea($attrName, $inputOptions = [], $helperOptions = []) + { + $this->input('textArea', $attrName, $inputOptions, $helperOptions); + } - } + public function booleanSelect($attrName, $inputOptions = [], $helperOptions = []) + { + $resources = []; - public function simpleSearchServidor($attrName, $inputOptions = array(), $helperOptions = array()) { + if (isset($inputOptions['prompt'])) { + $resources[''] = $inputOptions['prompt']; + } - $this->simpleSearchResourceInput('simpleSearchServidor', $attrName, $inputOptions, $helperOptions); + $resources += [0 => 'Não', 1 => 'Sim']; + $inputOptions['resources'] = $resources; + $this->select($attrName, $inputOptions, $helperOptions); + } - } + public function simpleSearch($objectName, $attrName, $inputOptions = [], $helperOptions = []) + { + $options = $this->mergeInputOptions($inputOptions, $helperOptions); - public function simpleSearchEscola($attrName, $inputOptions = array(), $helperOptions = array()) { + $helperClassName = 'Portabilis_View_Helper_Input_SimpleSearch'; + $this->includeHelper($helperClassName); - $this->simpleSearchResourceInput('simpleSearchEscola', $attrName, $inputOptions, $helperOptions); + $helper = new $helperClassName($this->viewInstance, $this); + $helper->simpleSearch($objectName, $attrName, $options); + } - } + public function simpleSearchPessoa($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchPessoa', $attrName, $inputOptions, $helperOptions); + } - public function simpleSearchProjeto($attrName, $inputOptions = array(), $helperOptions = array()) { + public function simpleSearchPais($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchPais', $attrName, $inputOptions, $helperOptions); + } - $this->simpleSearchResourceInput('simpleSearchProjeto', $attrName, $inputOptions, $helperOptions); + public function simpleSearchMunicipio($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchMunicipio', $attrName, $inputOptions, $helperOptions); + } - } + public function simpleSearchMatricula($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchMatricula', $attrName, $inputOptions, $helperOptions); + } - public function simpleSearchMenu($attrName, $inputOptions = array(), $helperOptions = array()) { + public function simpleSearchAluno($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchAluno', $attrName, $inputOptions, $helperOptions); + } - $this->simpleSearchResourceInput('simpleSearchMenu', $attrName, $inputOptions, $helperOptions); + public function simpleSearchEmpresa($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchEmpresa', $attrName, $inputOptions, $helperOptions); + } - } + public function simpleSearchPessoaj($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchPessoaj', $attrName, $inputOptions, $helperOptions); + } - public function simpleSearchCliente($attrName, $inputOptions = array(), $helperOptions = array()) { + public function simpleSearchMotorista($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchMotorista', $attrName, $inputOptions, $helperOptions); + } - $this->simpleSearchResourceInput('simpleSearchCliente', $attrName, $inputOptions, $helperOptions); + public function simpleSearchPonto($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchPonto', $attrName, $inputOptions, $helperOptions); + } - } + public function simpleSearchRota($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchRota', $attrName, $inputOptions, $helperOptions); + } - public function simpleSearchAcervo($attrName, $inputOptions = array(), $helperOptions = array()) { + public function simpleSearchVeiculo($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchVeiculo', $attrName, $inputOptions, $helperOptions); + } - $this->simpleSearchResourceInput('simpleSearchAcervo', $attrName, $inputOptions, $helperOptions); + public function simpleSearchBairro($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchBairro', $attrName, $inputOptions, $helperOptions); + } - } + public function simpleSearchDistrito($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchDistrito', $attrName, $inputOptions, $helperOptions); + } - // multiple search resource input helper + public function simpleSearchLogradouro($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchLogradouro', $attrName, $inputOptions, $helperOptions); + } + public function simpleSearchIes($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchIes', $attrName, $inputOptions, $helperOptions); + } - /*public function multipleSearchDeficienciasAjax($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchDeficiencias', $attrName, $inputOptions, $helperOptions); - }*/ + public function simpleSearchRotinasAuditoria($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchRotinasAuditoria', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchDeficiencias($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchDeficiencias', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchCursoSuperior($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchCursoSuperior', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchAssuntos($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchAssuntos', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchCartorioInep($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchCartorioInep', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchCategoriaObra($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchCategoriaObra', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchServidor($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchServidor', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchAutores($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchAutores', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchEscola($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchEscola', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchEtapacurso($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchEtapacurso', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchProjeto($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchProjeto', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchComponenteCurricular($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchComponenteCurricular', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchMenu($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchMenu', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchAreasConhecimento($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchAreasConhecimento', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchCliente($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchCliente', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchCursoAluno($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchCursoAluno', $attrName, $inputOptions, $helperOptions); - } + public function simpleSearchAcervo($attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput('simpleSearchAcervo', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchBeneficios($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchBeneficios', $attrName, $inputOptions, $helperOptions); - } + public function multipleSearchDeficiencias($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchDeficiencias', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchEscola($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchEscola', $attrName, $inputOptions, $helperOptions); - } + public function multipleSearchAssuntos($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchAssuntos', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchCurso($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchCurso', $attrName, $inputOptions, $helperOptions); - } + public function multipleSearchCategoriaObra($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchCategoriaObra', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchDocumentosAtestadoVaga($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchDocumentosAtestadoVaga', $attrName, $inputOptions, $helperOptions); - } + public function multipleSearchAutores($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchAutores', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchSerie($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchSerie', $attrName, $inputOptions, $helperOptions); - } + public function multipleSearchEtapacurso($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchEtapacurso', $attrName, $inputOptions, $helperOptions); + } - public function multipleSearchCustom($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchCustom', $attrName, $inputOptions, $helperOptions); - } + public function multipleSearchComponenteCurricular($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchComponenteCurricular', $attrName, $inputOptions, $helperOptions); + } + public function multipleSearchAreasConhecimento($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchAreasConhecimento', $attrName, $inputOptions, $helperOptions); + } - /*public function multipleSearchAjaxAreasConhecimento($attrName, $inputOptions = array(), $helperOptions = array()) { - $this->multipleSearchResourceInput('multipleSearchAjaxAreasConhecimento', $attrName, $inputOptions, $helperOptions); - }*/ + public function multipleSearchCursoAluno($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchCursoAluno', $attrName, $inputOptions, $helperOptions); + } - // resource input helpers + public function multipleSearchBeneficios($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchBeneficios', $attrName, $inputOptions, $helperOptions); + } - public function religiao($inputOptions = array(), $helperOptions = array()) { - $this->resourceInput('religiao', $this->mergeInputOptions($inputOptions, $helperOptions)); - } + public function multipleSearchEscola($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchEscola', $attrName, $inputOptions, $helperOptions); + } - public function beneficio($inputOptions = array(), $helperOptions = array()) { - $this->resourceInput('beneficio', $this->mergeInputOptions($inputOptions, $helperOptions)); - } + public function multipleSearchCurso($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchCurso', $attrName, $inputOptions, $helperOptions); + } - public function estadoCivil($inputOptions = array(), $helperOptions = array()) { - $this->resourceInput('estadoCivil', $this->mergeInputOptions($inputOptions, $helperOptions)); - } + public function multipleSearchDocumentosAtestadoVaga($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchDocumentosAtestadoVaga', $attrName, $inputOptions, $helperOptions); + } - public function turmaTurno($inputOptions = array(), $helperOptions = array()) { - $this->resourceInput('turmaTurno', $this->mergeInputOptions($inputOptions, $helperOptions)); - } + public function multipleSearchSerie($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchSerie', $attrName, $inputOptions, $helperOptions); + } - public function uf($inputOptions = array(), $helperOptions = array()) { - $this->resourceInput('uf', $this->mergeInputOptions($inputOptions, $helperOptions)); - } + public function multipleSearchCustom($attrName, $inputOptions = [], $helperOptions = []) + { + $this->multipleSearchResourceInput('multipleSearchCustom', $attrName, $inputOptions, $helperOptions); + } - public function tipoLogradouro($inputOptions = array(), $helperOptions = array()) { - $this->resourceInput('tipoLogradouro', $this->mergeInputOptions($inputOptions, $helperOptions)); - } + public function religiao($inputOptions = [], $helperOptions = []) + { + $this->resourceInput('religiao', $this->mergeInputOptions($inputOptions, $helperOptions)); + } - // protected methods + public function beneficio($inputOptions = [], $helperOptions = []) + { + $this->resourceInput('beneficio', $this->mergeInputOptions($inputOptions, $helperOptions)); + } - protected function resourceInput($helperName, $options = array()) { - $helperClassName = "Portabilis_View_Helper_Input_Resource_" . ucfirst($helperName); + public function estadoCivil($inputOptions = [], $helperOptions = []) + { + $this->resourceInput('estadoCivil', $this->mergeInputOptions($inputOptions, $helperOptions)); + } - $this->includeHelper($helperClassName); - $helper = new $helperClassName($this->viewInstance, $this); - $helper->$helperName($options); - } + public function turmaTurno($inputOptions = [], $helperOptions = []) + { + $this->resourceInput('turmaTurno', $this->mergeInputOptions($inputOptions, $helperOptions)); + } - protected function simpleSearchResourceInput($helperName, $attrName, $inputOptions = array(), $helperOptions = array()) { + public function uf($inputOptions = [], $helperOptions = []) + { + $this->resourceInput('uf', $this->mergeInputOptions($inputOptions, $helperOptions)); + } - $options = $this->mergeInputOptions($inputOptions, $helperOptions); + public function tipoLogradouro($inputOptions = [], $helperOptions = []) + { + $this->resourceInput('tipoLogradouro', $this->mergeInputOptions($inputOptions, $helperOptions)); + } - $helperClassName = 'Portabilis_View_Helper_Input_Resource_' . ucfirst($helperName); + protected function resourceInput($helperName, $options = []) + { + $helperClassName = 'Portabilis_View_Helper_Input_Resource_' . ucfirst($helperName); - $this->includeHelper($helperClassName); + $this->includeHelper($helperClassName); + $helper = new $helperClassName($this->viewInstance, $this); + $helper->$helperName($options); + } - $helper = new $helperClassName($this->viewInstance, $this); + protected function simpleSearchResourceInput($helperName, $attrName, $inputOptions = [], $helperOptions = []) + { + $options = $this->mergeInputOptions($inputOptions, $helperOptions); - $helper->$helperName($attrName, $options); + $helperClassName = 'Portabilis_View_Helper_Input_Resource_' . ucfirst($helperName); + $this->includeHelper($helperClassName); - } + $helper = new $helperClassName($this->viewInstance, $this); - protected function multipleSearchResourceInput($helperName, $attrName, $inputOptions = array(), $helperOptions = array()) { - $this->simpleSearchResourceInput($helperName, $attrName, $inputOptions, $helperOptions); - } + $helper->$helperName($attrName, $options); + } - protected function includeHelper($helperClassName) { - $classPath = str_replace('_', '/', $helperClassName) . '.php'; + protected function multipleSearchResourceInput($helperName, $attrName, $inputOptions = [], $helperOptions = []) + { + $this->simpleSearchResourceInput($helperName, $attrName, $inputOptions, $helperOptions); + } - // usado include_once para continuar execução script mesmo que o path inexista. - include_once $classPath; + protected function includeHelper($helperClassName) + { + $classPath = str_replace('_', '/', $helperClassName) . '.php'; - if (! class_exists($helperClassName)) - throw new CoreExt_Exception("Class '$helperClassName' not found in path '$classPath'"); - } + include_once $classPath; - protected function mergeInputOptions($inputOptions = array(), $helperOptions = array()) { - if (! empty($inputOptions) && isset($helperOptions['options'])) - throw new Exception("Don't send \$inputOptions and \$helperOptions['options'] at the same time!"); + if (!class_exists($helperClassName)) { + throw new CoreExt_Exception("Class '$helperClassName' not found in path '$classPath'"); + } + } - $defaultOptions = array('options' => $inputOptions); - $options = Portabilis_Array_Utils::merge($helperOptions, $defaultOptions); + protected function mergeInputOptions($inputOptions = [], $helperOptions = []) + { + if (!empty($inputOptions) && isset($helperOptions['options'])) { + throw new Exception('Don\'t send $inputOptions and $helperOptions[\'options\'] at the same time!'); + } - //foreach($helperOptions as $k => $v) { - // $options[$k] = $v; - //} + $defaultOptions = ['options' => $inputOptions]; + $options = Portabilis_Array_Utils::merge($helperOptions, $defaultOptions); - return $options; - } + return $options; + } } diff --git a/ieducar/lib/Utils/FileStream.class.php b/ieducar/lib/Utils/FileStream.class.php index 5c279c1f0c..7b5c615670 100644 --- a/ieducar/lib/Utils/FileStream.class.php +++ b/ieducar/lib/Utils/FileStream.class.php @@ -2,19 +2,19 @@ class FileStream { - /** - * Instância da classe Mimetype - * - * @var Mimetype - */ - protected $mimetype = null; + /** + * Instância da classe Mimetype + * + * @var Mimetype + */ + protected $mimetype = null; /** * Caminho do arquivo para stream * * @var string */ - protected $filepath = null; + protected $filepath = null; /** * Array de diretórios permitidos para stream de arquivos. @@ -32,6 +32,7 @@ class FileStream public function __construct(Mimetype $mimetype, array $allowedDirs = []) { $this->mimetype = $mimetype; + $this->setAllowedDirectories((array) $allowedDirs); } @@ -71,11 +72,11 @@ protected function isReadable($filepath) { $fileinfo = pathinfo($filepath); - if (! $this->isDirectoryAllowed($fileinfo['dirname'])) { + if (!$this->isDirectoryAllowed($fileinfo['dirname'])) { throw new Exception('Acesso ao diretório negado.'); } - if (! is_readable($filepath)) { + if (!is_readable($filepath)) { throw new Exception('Arquivo não existe.'); } } diff --git a/ieducar/lib/Utils/Mimetype.class.php b/ieducar/lib/Utils/Mimetype.class.php index 26ce90b1ac..804e34f6f9 100644 --- a/ieducar/lib/Utils/Mimetype.class.php +++ b/ieducar/lib/Utils/Mimetype.class.php @@ -6,7 +6,7 @@ public function getType($filename) { $filename = basename($filename); $filename = explode('.', $filename); - $filename = $filename[count($filename)-1]; + $filename = $filename[count($filename) - 1]; return $this->privFindType($filename); } diff --git a/ieducar/modules/Api/Views/DiarioController.php b/ieducar/modules/Api/Views/DiarioController.php index f0b7225edd..181e515fae 100644 --- a/ieducar/modules/Api/Views/DiarioController.php +++ b/ieducar/modules/Api/Views/DiarioController.php @@ -206,6 +206,10 @@ protected function postNotas() continue; } + if (! $serviceBoletim = $this->serviceBoletim($turmaId, $alunoId)) { + continue; + } + $valor = $notaTurmaAlunoDisciplina['nota']; $notaRecuperacao = $notaTurmaAlunoDisciplina['recuperacao']; $nomeCampoRecuperacao = $this->defineCampoTipoRecuperacao($matriculaId); @@ -217,6 +221,20 @@ protected function postNotas() $valorNota = $recuperacaoEspecifica ? $valor : $notaAposRecuperacao; + $regra = $serviceBoletim->getRegra(); + + if ($valorNota > $regra->notaMaximaGeral) { + $this->messenger->append("A nota {$valorNota} está acima da configurada para nota máxima geral que é {$regra->notaMaximaGeral}.", 'error'); + + return false; + } + + if ($valorNota < $regra->notaMinimaGeral) { + $this->messenger->append("A nota {$valorNota} está abaixo da configurada para nota mínima geral que é {$regra->notaMinimaGeral}.", 'error'); + + return false; + } + $array_nota = [ 'componenteCurricular' => $componenteCurricularId, 'nota' => $valorNota, @@ -229,10 +247,6 @@ protected function postNotas() $nota = new Avaliacao_Model_NotaComponente($array_nota); - if (! $serviceBoletim = $this->serviceBoletim($turmaId, $alunoId)) { - continue; - } - try { $serviceBoletim->verificaNotasLancadasNasEtapasAnteriores( $etapa, $componenteCurricularId @@ -299,6 +313,18 @@ protected function postRecuperacoes() $notaAposRecuperacao = (($notaRecuperacao > $notaOriginal) ? $notaRecuperacao : $notaOriginal); $valorNota = is_null($recuperacaoEspecifica) ? $notaOriginal : $notaAposRecuperacao; + if (! $serviceBoletim = $this->serviceBoletim($turmaId, $alunoId)) { + continue; + } + + $regra = $serviceBoletim->getRegra(); + + if ($valorNota > $regra->notaMaximaExameFinal) { + $this->messenger->append("A nota {$valorNota} está acima da configurada para nota máxima para exame que é {$regra->notaMaximaGeral}.", 'error'); + + return false; + } + $notaOriginal = $this->truncate($notaOriginal, 4); $array_nota = [ 'componenteCurricular' => $componenteCurricularId, diff --git a/ieducar/modules/Api/Views/ServidorController.php b/ieducar/modules/Api/Views/ServidorController.php index bff54813ec..a94b7c183a 100644 --- a/ieducar/modules/Api/Views/ServidorController.php +++ b/ieducar/modules/Api/Views/ServidorController.php @@ -98,6 +98,7 @@ protected function getServidoresDisciplinasTurmas() AND ccae.componente_curricular_id = ptd.componente_curricular_id) WHERE s.ref_cod_instituicao = $1 AND pt.ano = $2 + AND $2 = any(ccae.anos_letivos) GROUP BY pt.id, s.cod_servidor, p.nome, pt.turma_id, pt.permite_lancar_faltas_componente, ptd.componente_curricular_id, ccae.tipo_nota, s.ativo'; $_servidores = $this->fetchPreparedQuery($sql, [$instituicaoId, $ano]); diff --git a/ieducar/modules/Avaliacao/Service/Boletim.php b/ieducar/modules/Avaliacao/Service/Boletim.php index 2ab8b93b8f..81ed56b5ab 100644 --- a/ieducar/modules/Avaliacao/Service/Boletim.php +++ b/ieducar/modules/Avaliacao/Service/Boletim.php @@ -944,14 +944,26 @@ protected function _setMatriculaInfo() $matricula = App_Model_IedFinder::getMatricula($codMatricula); + $maiorEtapaUtilizada = []; + + // Foi preciso adicionar esta validação pois é possível filtrar sem + // selecionar um componente curricular, neste caso um erro SQL era gerado. + + if ($componenteCurricularId = $this->getComponenteCurricularId()) { + $maiorEtapaUtilizada = explode(',', App_Model_IedFinder::getEtapasComponente($matricula['ref_cod_turma'], $componenteCurricularId)); + } + $etapas = App_Model_IedFinder::getQuantidadeDeModulosMatricula($codMatricula, $matricula); - $etapaAtual = $_GET['etapa'] == 'Rc' ? $etapas : $_GET['etapa']; + + $maiorEtapaUtilizada = count($maiorEtapaUtilizada) ? max($maiorEtapaUtilizada) : $etapas; + + $etapaAtual = $_GET['etapa'] == 'Rc' ? $maiorEtapaUtilizada : $_GET['etapa']; $this->_setRegra(App_Model_IedFinder::getRegraAvaliacaoPorMatricula( - $codMatricula, $this->getRegraDataMapper(), $matricula - )); + $codMatricula, $this->getRegraDataMapper(), $matricula + )); - $this->_setComponentes(App_Model_IedFinder::getComponentesPorMatricula($codMatricula, $this->getComponenteDataMapper(), $this->getComponenteTurmaDataMapper(), $this->getComponenteCurricularId(), $etapaAtual, null, $matricula)); + $this->_setComponentes(App_Model_IedFinder::getComponentesPorMatricula($codMatricula, $this->getComponenteDataMapper(), $this->getComponenteTurmaDataMapper(), $componenteCurricularId, $etapaAtual, null, $matricula)); $this->setOption('matriculaData', $matricula); $this->setOption('aprovado', $matricula['aprovado']); @@ -1238,6 +1250,7 @@ function getSituacaoNotaFalta($flagSituacaoNota, $flagSituacaoFalta) $situacao->andamento = TRUE; break; case App_Model_MatriculaSituacao::APROVADO_APOS_EXAME: + $situacao->andamento = FALSE; $situacao->recuperacao = TRUE; break; case App_Model_MatriculaSituacao::APROVADO_COM_DEPENDENCIA: @@ -1266,30 +1279,34 @@ function getSituacaoNotaFalta($flagSituacaoNota, $flagSituacaoFalta) $situacoesFinais = array(App_Model_MatriculaSituacao::REPROVADO, App_Model_MatriculaSituacao::APROVADO, App_Model_MatriculaSituacao::APROVADO_APOS_EXAME); $andamento = (in_array($flagSituacaoNota, $situacoesFinais)) ? FALSE : TRUE; } - $situacao->andamento = FALSE; + + if ($flagSituacaoNota == App_Model_MatriculaSituacao::EM_EXAME) { + $andamento = TRUE; + } + $situacao->andamento = $andamento; break; case App_Model_MatriculaSituacao::APROVADO: $situacao->retidoFalta = FALSE; break; } - // seta situacao geral - if ($situacao->andamento and $situacao->recuperacao) - $situacao->situacao = App_Model_MatriculaSituacao::EM_EXAME; + // seta situacao geral + if ($situacao->andamento and $situacao->recuperacao) + $situacao->situacao = App_Model_MatriculaSituacao::EM_EXAME; - elseif (! $situacao->andamento and $situacao->aprovado and $situacao->recuperacao) - $situacao->situacao = App_Model_MatriculaSituacao::APROVADO_APOS_EXAME; + elseif (! $situacao->andamento and (!$situacao->aprovado || $situacao->retidoFalta)) + $situacao->situacao = App_Model_MatriculaSituacao::REPROVADO; - elseif (! $situacao->andamento and $situacao->aprovado and $situacao->aprovadoComDependencia) - $situacao->situacao = App_Model_MatriculaSituacao::APROVADO_COM_DEPENDENCIA; + elseif (! $situacao->andamento and $situacao->aprovado and $situacao->recuperacao) + $situacao->situacao = App_Model_MatriculaSituacao::APROVADO_APOS_EXAME; - elseif (! $situacao->andamento and (!$situacao->aprovado || $situacao->retidoFalta)) - $situacao->situacao = App_Model_MatriculaSituacao::REPROVADO; + elseif (! $situacao->andamento and $situacao->aprovado and $situacao->aprovadoComDependencia) + $situacao->situacao = App_Model_MatriculaSituacao::APROVADO_COM_DEPENDENCIA; - elseif (! $situacao->andamento and $situacao->aprovado) - $situacao->situacao = App_Model_MatriculaSituacao::APROVADO; + elseif (! $situacao->andamento and $situacao->aprovado) + $situacao->situacao = App_Model_MatriculaSituacao::APROVADO; - return $situacao; + return $situacao; } @@ -2763,13 +2780,18 @@ protected function _calculateNotasRecuperacoesEspecificas($id, $data = array()){ $regrasRecuperacoes = $this->getRegra()->findRegraRecuperacao(); $cont = 0; + + if (count($regrasRecuperacoes)) { + $data['Se'] = 0; + } + foreach ($regrasRecuperacoes as $key => $_regraRecuperacao) { $cont++; $notaRecuperacao = $this->getNotaComponente($id, $_regraRecuperacao->getLastEtapa()); if($notaRecuperacao && is_numeric($notaRecuperacao->notaRecuperacaoEspecifica)){ // Caso tenha nota de recuperação para regra atual, atribuí variável RE+N + $substituiMenorNota = (bool)$_regraRecuperacao->substituiMenorNota; $data['RSP'.$cont] = $notaRecuperacao->notaRecuperacaoEspecifica; - $notaRecuperacao->notaRecuperacaoEspecifica; $somaEtapasRecuperacao = 0; $countEtapasRecuperacao = 0; @@ -2781,7 +2803,12 @@ protected function _calculateNotasRecuperacoesEspecificas($id, $data = array()){ $mediaEtapasRecuperacao = $somaEtapasRecuperacao / $countEtapasRecuperacao; $mediaEtapasRecuperacaoComRecuperacao = ($mediaEtapasRecuperacao + $notaRecuperacao->notaRecuperacaoEspecifica) / 2; - $substituiMenorNota = (bool)$_regraRecuperacao->substituiMenorNota; + + if (!$substituiMenorNota) { + $data['Se'] += $data['RSP'.$cont] ?? $somaEtapasRecuperacao; + } else { + $data['Se'] += $data['RSP'.$cont] > $mediaEtapasRecuperacao ? $data['RSP'.$cont] * $countEtapasRecuperacao : $somaEtapasRecuperacao; + } // Caso média com recuperação seja maior que média das somas das etapas sem recuperação, atribuí variável MRE+N if(!$substituiMenorNota || $mediaEtapasRecuperacaoComRecuperacao > $mediaEtapasRecuperacao) @@ -2805,7 +2832,7 @@ protected function _calculateNotasRecuperacoesEspecificas($id, $data = array()){ $somaEtapasRecuperacao += $data['E' . $__etapa]; $countEtapasRecuperacao++; } - + $data['Se'] += $somaEtapasRecuperacao; $data['RSPM'.$cont] = $somaEtapasRecuperacao / $countEtapasRecuperacao; $data['RSPS'.$cont] = $somaEtapasRecuperacao; } @@ -2904,29 +2931,28 @@ public function getCurrentComponenteCurricular(){ */ public function saveNotas() { - if ($this->getRegra()->get('tipoNota') == RegraAvaliacao_Model_Nota_TipoValor::NENHUM) { - return $this; - } - - $notaAluno = $this->_getNotaAluno(); - $notas = $this->getNotas(); - + if ($this->getRegra()->get('tipoNota') == RegraAvaliacao_Model_Nota_TipoValor::NENHUM) { + return $this; + } - foreach ($notas as $nota) { - $nota->notaAluno = $notaAluno; - if($nota instanceof Avaliacao_Model_NotaComponente){ - $nota->id = $this->_getNotaIdEtapa($nota); - $this->getNotaComponenteDataMapper()->save($nota); + $notaAluno = $this->_getNotaAluno(); + $notas = $this->getNotas(); + + foreach ($notas as $nota) { + $nota->notaAluno = $notaAluno; + if($nota instanceof Avaliacao_Model_NotaComponente){ + $nota->id = $this->_getNotaIdEtapa($nota); + $this->getNotaComponenteDataMapper()->save($nota); - }elseif($nota instanceof Avaliacao_Model_NotaGeral){ - $nota->id = $this->_getNotaGeralIdEtapa($nota); - $this->getNotaGeralDataMapper()->save($nota); + }elseif($nota instanceof Avaliacao_Model_NotaGeral){ + $nota->id = $this->_getNotaGeralIdEtapa($nota); + $this->getNotaGeralDataMapper()->save($nota); + } } - } - // Atualiza as médias - $this->_updateNotaComponenteMedia(); - return $this; + // Atualiza as médias + $this->_updateNotaComponenteMedia(); + return $this; } /** @@ -3275,26 +3301,32 @@ protected function _updateMatricula($matricula, $usuario, $promover) return App_Model_Matricula::atualizaMatricula($matricula, $usuario, $promover); } - public function deleteNota($etapa, $ComponenteCurricularId) { - // zera nota antes de deletar, para que a media seja recalculada - try { - $nota = new Avaliacao_Model_NotaComponente(array( - 'componenteCurricular' => $ComponenteCurricularId, - 'nota' => 0, - 'etapa' => $etapa - )); - $this->addNota($nota); - $this->save(); - } - catch (Exception $e) { - error_log("Excessao ignorada ao zerar nota a ser removida: " . $e->getMessage()); + if ($etapa != 'Rc') { + try { + $nota = new Avaliacao_Model_NotaComponente(array( + 'componenteCurricular' => $ComponenteCurricularId, + 'nota' => 0, + 'etapa' => $etapa + )); + $this->addNota($nota); + $this->save(); + } + catch (Exception $e) { + error_log("Excessao ignorada ao zerar nota a ser removida: " . $e->getMessage()); + } } $nota = $this->getNotaComponente($ComponenteCurricularId, $etapa); $this->getNotaComponenteDataMapper()->delete($nota); + try { + $this->save(); + } catch (Exception $e) { + error_log("Excessao ignorada ao zerar nota a ser removida: " . $e->getMessage()); + } + return $this; } diff --git a/ieducar/modules/Avaliacao/Views/PromocaoApiController.php b/ieducar/modules/Avaliacao/Views/PromocaoApiController.php index 8775336e80..10d67b31cc 100644 --- a/ieducar/modules/Avaliacao/Views/PromocaoApiController.php +++ b/ieducar/modules/Avaliacao/Views/PromocaoApiController.php @@ -51,8 +51,7 @@ class PromocaoApiController extends ApiCoreController protected $_processoAp = 644; protected function canAcceptRequest() { - return parent::canAcceptRequest() && - $this->validatesUserIsAdmin() && + return parent::canAcceptRequest() && $this->validatesPresenceOf('ano'); } diff --git a/ieducar/modules/ComponenteCurricular/Model/ComponenteDataMapper.php b/ieducar/modules/ComponenteCurricular/Model/ComponenteDataMapper.php index fd38f3084f..97e0d699cb 100644 --- a/ieducar/modules/ComponenteCurricular/Model/ComponenteDataMapper.php +++ b/ieducar/modules/ComponenteCurricular/Model/ComponenteDataMapper.php @@ -132,4 +132,26 @@ public function findComponenteCurricularAnoEscolar($componenteCurricular, $anoEs return $componenteCurricular; } + + /** + * Busca um componente curricular por nome. + * + * @param string $name + * + * @return CoreExt_Entity|null + * + * @throws Exception + */ + public function findByName($name) + { + $sql = "SELECT {$this->_getTableColumns()} FROM {$this->_getTableName()} WHERE nome ILIKE '%{$name}%'"; + + $this->_getDbAdapter()->Consulta($sql); + + if (empty($this->_getDbAdapter()->ProximoRegistro())) { + return null; + } + + return $this->_createEntityObject($this->_getDbAdapter()->Tupla()); + } } diff --git a/ieducar/modules/ComponenteCurricular/Model/TipoBase.php b/ieducar/modules/ComponenteCurricular/Model/TipoBase.php index 69239f462b..0fb408c187 100644 --- a/ieducar/modules/ComponenteCurricular/Model/TipoBase.php +++ b/ieducar/modules/ComponenteCurricular/Model/TipoBase.php @@ -4,6 +4,7 @@ class ComponenteCurricular_Model_TipoBase extends CoreExt_Enum { + const DEFAULT = self::COMUM; const COMUM = 1; const DIVERSIFICADA = 2; const PROFISSIONAL = 3; diff --git a/ieducar/modules/ComponenteCurricular/Views/EditController.php b/ieducar/modules/ComponenteCurricular/Views/EditController.php index e9bd1ec730..c94aea5bbc 100644 --- a/ieducar/modules/ComponenteCurricular/Views/EditController.php +++ b/ieducar/modules/ComponenteCurricular/Views/EditController.php @@ -123,7 +123,7 @@ public function Gerar() 'tipo_base', $this->_getLabel('tipo_base'), $tipoBase->getEnums(), - $this->getEntity()->get('tipo_base') + $this->getEntity()->get('tipo_base') ?? ComponenteCurricular_Model_TipoBase::DEFAULT ); // Área de conhecimento @@ -214,11 +214,3 @@ protected function _save() } } } - -//seta o radio automaticamente como primeiro valor -echo ''; diff --git a/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php b/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php index 76e2ad6d6e..3b385ad971 100644 --- a/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php +++ b/ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php @@ -634,7 +634,8 @@ protected function _createHistoricoDisciplinas($fields) $fields['falta'], $fields['ordenamento'], $fields['carga_horaria_disciplina'], - $fields['dependencia'] + $fields['dependencia'], + $fields['tipo_base'] ); $historicoDisciplina->cadastra(); } @@ -661,7 +662,7 @@ protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $mediaAreaConhecimento = $this->getRequest()->media_area_conhecimento; $processarMediaGeral = $this->getRequest()->processar_media_geral; $casasDecimais = $this->getService()->getRegra()->get('qtdCasasDecimais'); - $aprovadoDependencia = $this->getSituacaoMatricula($aluno['ref_cod_matricula']) == 12; + $aprovadoDependencia = $this->getSituacaoMatricula() == 12; foreach ($this->getService()->getComponentes() as $componenteCurricular) { if (!$this->shouldProcessAreaConhecimento($componenteCurricular->get('area_conhecimento'))) { @@ -672,7 +673,8 @@ protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $disciplinaDependencia = ($aprovadoDependencia && $reprovado); $nome = $componenteCurricular->nome; $ordenamento = $componenteCurricular->ordenamento; - $carga_horaria_disciplina = $componenteCurricular->carga_horaria_disciplina; + $tipo_base = $componenteCurricular->get('tipo_base'); + $carga_horaria_disciplina = $componenteCurricular->cargaHoraria; $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); $nota = ''; $notaConceitualNumerica = ''; @@ -716,6 +718,7 @@ protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['ordenamento'] = $componenteCurricular->area_conhecimento->ordenamento; $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['carga_horaria_disciplina'] = $componenteCurricular->area_conhecimento->carga_horaria_disciplina; $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['dependencia'] = $disciplinaDependencia; + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['tipo_base'] = $tipo_base; $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['count']++; } else { $this->_createHistoricoDisciplinas( @@ -728,7 +731,8 @@ protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, 'falta' => $this->getFalta($situacaoFaltasCc[$ccId]), 'ordenamento' => $ordenamento, 'carga_horaria_disciplina' => $carga_horaria_disciplina, - 'dependencia' => $disciplinaDependencia + 'dependencia' => $disciplinaDependencia, + 'tipo_base' => $tipo_base, ] ); } @@ -756,7 +760,8 @@ protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, 'falta' => round($value['falta'] / $value['count']), 'ordenamento' => $value['ordenamento'], 'carga_horaria_disciplina' => $value['carga_horaria_disciplina'], - 'dependencia' => $value['dependencia'] + 'dependencia' => $value['dependencia'], + 'tipo_base' => $tipo_base, ] ); } @@ -766,9 +771,24 @@ protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $alunoId); } } else { + + $i = 0; + foreach ($this->getRequest()->disciplinas as $disciplina) { $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId); + $i++; + + $tipo_base = ComponenteCurricular_Model_TipoBase::DEFAULT; + $ordenamento = $i; + + $componenteCurricular = (new ComponenteCurricular_Model_ComponenteDataMapper())->findByName($disciplina['nome']); + + if ($componenteCurricular) { + $ordenamento = $componenteCurricular->ordenamento; + $tipo_base = $componenteCurricular->get('tipo_base'); + } + $this->_createHistoricoDisciplinas( [ 'sequencial' => $sequencial, @@ -777,9 +797,10 @@ protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, 'nome' => $disciplina['nome'], 'nota' => $disciplina['nota'], 'falta' => $falta = $disciplina['falta'], - 'ordenamento' => $value['ordenamento'], - 'carga_horaria_disciplina' => $value['carga_horaria_disciplina'], - 'dependencia' => $value['dependencia'] + 'ordenamento' => $ordenamento, + 'carga_horaria_disciplina' => null, // Não existe esta informação + 'dependencia' => false, // Não existe esta informação + 'tipo_base' => $tipo_base, ] ); }