├── .codeclimate.yml ├── .editorconfig ├── .env.sample ├── .gitignore ├── .php-cs-fixer.php ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── README.md ├── composer.json ├── composer.lock ├── config ├── config.php ├── dependencies.php ├── dic.php ├── middleware.php └── routes.php ├── db └── migrations │ ├── 20211001205509_url.php │ ├── 20211001205541_url_log.php │ ├── 20211015134231_bin_to_uuid.php │ └── 20211015140735_uuid_to_bin.php ├── docker-compose.yml ├── docs └── smallish-screen.png ├── phinx.php ├── phpcs.xml ├── psalm.xml ├── public_html ├── .htaccess ├── css │ └── style.css ├── images │ └── meta-image.png ├── index.php └── js │ └── script.js ├── src ├── Adapter │ ├── Controllers │ │ ├── AccessUrlController.php │ │ ├── HomeController.php │ │ └── ShortenUrlController.php │ └── Repository │ │ └── Database │ │ └── DbLongUrlRepository.php ├── Domain │ ├── Entity │ │ └── LongUrl.php │ ├── Exceptions │ │ └── InvalidLongUrl.php │ ├── Repository │ │ └── LongUrlRepository.php │ ├── UseCase │ │ └── ShortenUrl │ │ │ ├── InputData.php │ │ │ ├── OutputData.php │ │ │ └── ShortenUrl.php │ └── ValueObject │ │ └── LongUrlType.php └── Shared │ ├── Adapter │ ├── Contracts │ │ ├── DatabaseOrm.php │ │ ├── Dto.php │ │ ├── TemplateEngine.php │ │ └── UuidGenerator.php │ ├── Controller │ │ ├── ControllerBase.php │ │ ├── RestController.php │ │ ├── TemplateController.php │ │ └── TemplateEngineFactory.php │ ├── DtoBase.php │ ├── Exception │ │ └── InvalidDtoParam.php │ ├── Middleware │ │ ├── SessionMiddleware.php │ │ ├── SlimFlashMiddleware.php │ │ └── TwigMiddleware.php │ └── RepositoryBase.php │ ├── Domain │ ├── Contracts │ │ ├── Entity.php │ │ ├── Repository.php │ │ └── ValueObject.php │ ├── EntityBase.php │ ├── Exceptions │ │ ├── InvalidEntityException.php │ │ └── InvalidUrlException.php │ ├── ValueObjectBase.php │ └── ValueObjects │ │ └── Url.php │ ├── Exception │ ├── Error.php │ ├── ExceptionBase.php │ ├── RuntimeException.php │ └── ValidationException.php │ └── Infra │ ├── PdoOrm.php │ ├── RamseyUiidAdapter.php │ └── TwigAdapter.php ├── templates ├── error.html.twig ├── index.html.twig ├── layouts │ ├── _messages.html.twig │ ├── base.html.twig │ └── blank.html.twig └── notfound.html.twig └── tests ├── Integration └── .gitkeep ├── TestCase.php ├── Unit └── .gitkeep ├── bootstrap.php └── phpunit.xml.sample /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | phpcodesniffer: 3 | enabled: true 4 | config: 5 | file_extensions: "php" 6 | standard: "PSR12" 7 | 8 | editorconfig: 9 | enabled: true 10 | config: 11 | editorconfig: .editorconfig 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | insert_final_newline = true 7 | indent_style = space 8 | indent_size = 4 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false 13 | 14 | [*.{js,yml,yaml}] 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /.env.sample: -------------------------------------------------------------------------------- 1 | DOCKER_APP_PORT=8082 2 | DOCKER_APP_PORT_SSL=443 3 | DOCKER_MYSQL_PORT=3306 4 | 5 | APP_NAME=smallish 6 | APP_ENV=dev 7 | APP_DEBUG=true 8 | APP_ENCODING=UTF-8 9 | APP_BASE_URL=https://localhost:8082 10 | APP_DEFAULT_LOCALE=pt_BR 11 | APP_DEFAULT_TIMEZONE=America/Sao_Paulo 12 | 13 | DB_HOST=smallish-db 14 | DB_PORT=3306 15 | DB_DATABASE=smallish 16 | DB_USER=root 17 | DB_PASSWORD= 18 | DB_CHARSET=utf8 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # phpstorm project files 2 | .idea 3 | 4 | # netbeans project files 5 | nbproject 6 | 7 | # zend studio for eclipse project files 8 | .buildpath 9 | .project 10 | .settings 11 | 12 | # windows thumbnail cache 13 | Thumbs.db 14 | 15 | # composer vendor dir 16 | /vendor 17 | 18 | # composer itself is not needed 19 | composer.phar 20 | 21 | # Mac DS_Store Files 22 | .DS_Store 23 | 24 | # phpunit itself is not needed 25 | phpunit.phar 26 | # local phpunit config 27 | tests/phpunit.xml 28 | 29 | .env 30 | phpunit.xml 31 | .php_cs.cache 32 | .phpunit.result.cache 33 | tests/coverage 34 | tests/.phpunit.result.cache 35 | tests/mutation 36 | .docker 37 | dumps 38 | var/* -------------------------------------------------------------------------------- /.php-cs-fixer.php: -------------------------------------------------------------------------------- 1 | notPath('vendor') 5 | ->in(__DIR__) 6 | ->name('*.php'); 7 | 8 | $config = new PhpCsFixer\Config(); 9 | 10 | $config 11 | ->setUsingCache(false) 12 | ->setFinder($finder) 13 | ->setRules( 14 | [ 15 | '@PSR12' => true, 16 | 'final_class' => true, 17 | 'static_lambda' => true, 18 | 'linebreak_after_opening_tag' => true, 19 | 'blank_line_after_opening_tag' => true, 20 | 'declare_strict_types' => true, 21 | 'array_syntax' => ['syntax' => 'short'], 22 | 'ordered_imports' => ['sort_algorithm' => 'length'], 23 | 'no_unused_imports' => true, 24 | 'is_null' => true, 25 | 'list_syntax' => [ 26 | 'syntax' => 'short', 27 | ], 28 | 'native_function_invocation' => [ 29 | 'exclude' => [], 30 | 'opcache-only' => true, 31 | ], 32 | 'lowercase_cast' => true, 33 | 'lowercase_static_reference' => true, 34 | 'mb_str_functions' => true, 35 | 'modernize_types_casting' => true, 36 | 'native_constant_invocation' => true, 37 | 'native_function_casing' => true, 38 | 'new_with_braces' => true, 39 | 'blank_line_before_statement' => [ 40 | 'statements' => ['declare',], 41 | ], 42 | 'return_type_declaration' => [ 43 | 'space_before' => 'none', 44 | ], 45 | ] 46 | ); 47 | 48 | return $config; 49 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct - Smallish 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to a positive environment for our 15 | community include: 16 | 17 | * Demonstrating empathy and kindness toward other people 18 | * Being respectful of differing opinions, viewpoints, and experiences 19 | * Giving and gracefully accepting constructive feedback 20 | * Accepting responsibility and apologizing to those affected by our mistakes, 21 | and learning from the experience 22 | * Focusing on what is best not just for us as individuals, but for the 23 | overall community 24 | 25 | Examples of unacceptable behavior include: 26 | 27 | * The use of sexualized language or imagery, and sexual attention or 28 | advances 29 | * Trolling, insulting or derogatory comments, and personal or political attacks 30 | * Public or private harassment 31 | * Publishing others' private information, such as a physical or email 32 | address, without their explicit permission 33 | * Other conduct which could reasonably be considered inappropriate in a 34 | professional setting 35 | 36 | ## Our Responsibilities 37 | 38 | Project maintainers are responsible for clarifying and enforcing our standards of 39 | acceptable behavior and will take appropriate and fair corrective action in 40 | response to any instances of unacceptable behavior. 41 | 42 | Project maintainers have the right and responsibility to remove, edit, or reject 43 | comments, commits, code, wiki edits, issues, and other contributions that are 44 | not aligned to this Code of Conduct, or to ban 45 | temporarily or permanently any contributor for other behaviors that they deem 46 | inappropriate, threatening, offensive, or harmful. 47 | 48 | ## Scope 49 | 50 | This Code of Conduct applies within all community spaces, and also applies when 51 | an individual is officially representing the community in public spaces. 52 | Examples of representing our community include using an official e-mail address, 53 | posting via an official social media account, or acting as an appointed 54 | representative at an online or offline event. 55 | 56 | ## Enforcement 57 | 58 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 59 | reported to the community leaders responsible for enforcement at . 60 | All complaints will be reviewed and investigated promptly and fairly. 61 | 62 | All community leaders are obligated to respect the privacy and security of the 63 | reporter of any incident. 64 | 65 | ## Attribution 66 | 67 | This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org/), version 68 | [1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/code_of_conduct.md) and 69 | [2.0](https://www.contributor-covenant.org/version/2/0/code_of_conduct/code_of_conduct.md), 70 | and was generated by [contributing-gen](https://github.com/bttger/contributing-gen). -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributing to Smallish 3 | 4 | First off, thanks for taking the time to contribute! ❤️ 5 | 6 | All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 7 | 8 | > And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: 9 | > - Star the project 10 | > - Tweet about it 11 | > - Refer this project in your project's readme 12 | > - Mention the project at local meetups and tell your friends/colleagues 13 | 14 | 15 | ## Table of Contents 16 | 17 | - [Code of Conduct](#code-of-conduct) 18 | - [I Have a Question](#i-have-a-question) 19 | - [I Want To Contribute](#i-want-to-contribute) 20 | - [Reporting Bugs](#reporting-bugs) 21 | - [Suggesting Enhancements](#suggesting-enhancements) 22 | - [Your First Code Contribution](#your-first-code-contribution) 23 | - [Improving The Documentation](#improving-the-documentation) 24 | - [Styleguides](#styleguides) 25 | - [Commit Messages](#commit-messages) 26 | - [Join The Project Team](#join-the-project-team) 27 | 28 | 29 | ## Code of Conduct 30 | 31 | This project and everyone participating in it is governed by the 32 | [Smallish Code of Conduct](https://github.com/dersonsena/small-sh/blob/master/CODE_OF_CONDUCT.md). 33 | By participating, you are expected to uphold this code. Please report unacceptable behavior 34 | to . 35 | 36 | 37 | ## I Have a Question 38 | 39 | > If you want to ask a question, we assume that you have read the available [Documentation](https://github.com/dersonsena/small-sh). 40 | 41 | Before you ask a question, it is best to search for existing [Issues](https://github.com/dersonsena/small-sh/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. 42 | 43 | If you then still feel the need to ask a question and need clarification, we recommend the following: 44 | 45 | - Open an [Issue](https://github.com/dersonsena/small-sh/issues/new). 46 | - Provide as much context as you can about what you're running into. 47 | - Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. 48 | 49 | We will then take care of the issue as soon as possible. 50 | 51 | 65 | 66 | ## I Want To Contribute 67 | 68 | > ### Legal Notice 69 | > When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. 70 | 71 | ### Reporting Bugs 72 | 73 | 74 | #### Before Submitting a Bug Report 75 | 76 | A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. 77 | 78 | - Make sure that you are using the latest version. 79 | - Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://github.com/dersonsena/small-sh). If you are looking for support, you might want to check [this section](#i-have-a-question)). 80 | - To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/dersonsena/small-sh/issues?q=label%3Abug). 81 | - Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. 82 | - Collect information about the bug: 83 | - Stack trace (Traceback) 84 | - OS, Platform and Version (Windows, Linux, macOS, x86, ARM) 85 | - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. 86 | - Possibly your input and the output 87 | - Can you reliably reproduce the issue? And can you also reproduce it with older versions? 88 | 89 | 90 | #### How Do I Submit a Good Bug Report? 91 | 92 | > You must never report security related issues, vulnerabilities or bugs to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . 93 | 94 | 95 | We use GitHub issues to track bugs and errors. If you run into an issue with the project: 96 | 97 | - Open an [Issue](https://github.com/dersonsena/small-sh/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) 98 | - Explain the behavior you would expect and the actual behavior. 99 | - Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. 100 | - Provide the information you collected in the previous section. 101 | 102 | Once it's filed: 103 | 104 | - The project team will label the issue accordingly. 105 | - A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. 106 | - If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution). 107 | 108 | 109 | 110 | 111 | ### Suggesting Enhancements 112 | 113 | This section guides you through submitting an enhancement suggestion for Smallish, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. 114 | 115 | 116 | #### Before Submitting an Enhancement 117 | 118 | - Make sure that you are using the latest version. 119 | - Read the [documentation](https://github.com/dersonsena/small-sh) carefully and find out if the functionality is already covered, maybe by an individual configuration. 120 | - Perform a [search](https://github.com/dersonsena/small-sh/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. 121 | - Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. 122 | 123 | 124 | #### How Do I Submit a Good Enhancement Suggestion? 125 | 126 | Enhancement suggestions are tracked as [GitHub issues](https://github.com/dersonsena/small-sh/issues). 127 | 128 | - Use a **clear and descriptive title** for the issue to identify the suggestion. 129 | - Provide a **step-by-step description of the suggested enhancement** in as many details as possible. 130 | - **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. 131 | - You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. 132 | - **Explain why this enhancement would be useful** to most Smallish users. You may also want to point out the other projects that solved it better and which could serve as inspiration. 133 | 134 | 135 | 136 | ### Your First Code Contribution 137 | 141 | 142 | ### Improving The Documentation 143 | 147 | 148 | ## Styleguides 149 | ### Commit Messages 150 | 153 | 154 | ## Join The Project Team 155 | 156 | 157 | 158 | ## Attribution 159 | This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! 160 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:8.0.9-alpine3.14 2 | LABEL maintainer="dersonsena@gmail.com" 3 | 4 | RUN apk update && apk add --no-cache --update \ 5 | nano \ 6 | g++ \ 7 | gcc \ 8 | curl \ 9 | curl-dev \ 10 | zip \ 11 | unzip \ 12 | wget \ 13 | make \ 14 | bash \ 15 | git \ 16 | icu-dev \ 17 | oniguruma-dev \ 18 | tzdata \ 19 | libzip-dev \ 20 | libmcrypt-dev \ 21 | autoconf 22 | 23 | RUN docker-php-ext-install pdo \ 24 | && docker-php-ext-install pdo_mysql \ 25 | && docker-php-ext-install mysqli \ 26 | && docker-php-ext-install intl \ 27 | && docker-php-ext-install mbstring \ 28 | && docker-php-ext-install zip \ 29 | && docker-php-ext-install curl \ 30 | && php -m 31 | 32 | # Installing Mcrypt extension 33 | RUN pecl install -o -f mcrypt && docker-php-ext-enable mcrypt 34 | 35 | RUN rm -rf /var/cache/apk/* 36 | 37 | COPY --from=composer /usr/bin/composer /usr/bin/composer 38 | 39 | EXPOSE 80 40 | 41 | WORKDIR /usr/src/app -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Smallish 2 | 3 | FREE Shortener and OPEN SOURCE, because your urls can be small and free 4 | 5 | ![smallish-screen](docs/smallish-screen.png) 6 | 7 | @todo 8 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dersonsena/smallish", 3 | "description": "Smallish", 4 | "license": "MIT", 5 | "authors": [ 6 | { 7 | "name": "Kilderson Sena", 8 | "email": "dersonsena@gmail.com" 9 | } 10 | ], 11 | "scripts": { 12 | "start": "php -S localhost:8080 -t public_html", 13 | "test": "phpunit --testdox --configuration tests/phpunit.xml", 14 | "test-unit": "phpunit --configuration tests/phpunit.xml --testdox --testsuite unit", 15 | "test-integration": "phpunit --configuration tests/phpunit.xml --testdox --testsuite integration", 16 | "test-filter": "phpunit --configuration tests/phpunit.xml --filter ", 17 | "coverage": "phpunit --configuration tests/phpunit.xml --coverage-html tests/coverage/html", 18 | "coverage-ci": "phpunit --configuration tests/phpunit.xml --coverage-text --colors=never", 19 | "phpcs": "phpcs --standard=phpcs.xml", 20 | "phpcs-fixer": "php-cs-fixer fix --config=.php-cs-fixer.php --allow-risky yes", 21 | "phpcbf": "phpcbf -w -p", 22 | "psalm": "psalm --show-info=true" 23 | }, 24 | "require": { 25 | "php": "^8.0", 26 | "ext-intl": "*", 27 | "ext-json": "*", 28 | "ext-pdo": "*", 29 | "odan/session": "^5.1", 30 | "php-di/php-di": "^6.3", 31 | "ramsey/uuid": "^4.2", 32 | "slim/flash": "^0.4.0", 33 | "slim/psr7": "^1.4", 34 | "slim/slim": "^4.8", 35 | "slim/twig-view": "^3.2", 36 | "vlucas/phpdotenv": "^5.3" 37 | }, 38 | "require-dev": { 39 | "dg/bypass-finals": "^1.3", 40 | "fakerphp/faker": "^1.16", 41 | "friendsofphp/php-cs-fixer": "^3.1", 42 | "phpunit/phpunit": "^8.5", 43 | "robmorgan/phinx": "^0.12.8", 44 | "squizlabs/php_codesniffer": "^3.6", 45 | "vimeo/psalm": "^4.10" 46 | }, 47 | "config": { 48 | "optimize-autoloader": true, 49 | "preferred-install": "dist", 50 | "github-protocols": ["https"], 51 | "sort-packages": true, 52 | "process-timeout": 1800 53 | }, 54 | "autoload": { 55 | "psr-4": { 56 | "App\\": "src/" 57 | } 58 | }, 59 | "autoload-dev": { 60 | "psr-4": { 61 | "Tests\\": "tests/" 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | !APP_IS_PRODUCTION, 5 | 'baseUrl' => $_ENV['APP_BASE_URL'], 6 | 'session' => [ 7 | 'name' => 'smallish', 8 | 'cache_expire' => 0, 9 | 'cookie_httponly' => true, 10 | 'cookie_secure' => APP_IS_PRODUCTION 11 | ], 12 | 'twig' => [ 13 | 'templatePath' => ROOT_PATH . '/templates', 14 | 'cachePath' => APP_IS_PRODUCTION ? ROOT_PATH . '/var/cache' : false 15 | ], 16 | 'database' => [ 17 | 'host' => $_ENV['DB_HOST'], 18 | 'port' => $_ENV['DB_PORT'], 19 | 'username' => $_ENV['DB_USER'], 20 | 'password' => $_ENV['DB_PASSWORD'], 21 | 'dbname' => $_ENV['DB_DATABASE'], 22 | 'charset' => $_ENV['DB_CHARSET'] 23 | ], 24 | ]; 25 | -------------------------------------------------------------------------------- /config/dependencies.php: -------------------------------------------------------------------------------- 1 | addDefinitions([ 22 | SessionInterface::class => function (ContainerInterface $c) { 23 | $sessionParams = $c->get('config')['session']; 24 | $session = new PhpSession(); 25 | $session->setOptions($sessionParams); 26 | return $session; 27 | }, 28 | SessionMiddleware::class => function (ContainerInterface $c) { 29 | return new SessionMiddleware($c->get(SessionInterface::class)); 30 | }, 31 | Messages::class => function (ContainerInterface $c) { 32 | $storage = []; 33 | return new Messages($storage); 34 | }, 35 | DatabaseOrm::class => function (ContainerInterface $c) { 36 | return new PdoOrm($c->get('db')); 37 | }, 38 | UuidGenerator::class => DI\autowire(RamseyUiidAdapter::class), 39 | LongUrlRepository::class => function (ContainerInterface $c) { 40 | return new DbLongUrlRepository( 41 | $c->get(DatabaseOrm::class), 42 | $c->get(UuidGenerator::class), 43 | $c->get('config')['baseUrl'] 44 | ); 45 | }, 46 | TemplateEngine::class => DI\autowire(TwigAdapter::class) 47 | ]); 48 | }; 49 | -------------------------------------------------------------------------------- /config/dic.php: -------------------------------------------------------------------------------- 1 | build(); 14 | 15 | $container->set('config', function () { 16 | return require __DIR__ . DS . 'config.php'; 17 | }); 18 | 19 | $container->set('view', function () use ($container) { 20 | $config = $container->get('config'); 21 | $flash = $container->get(Messages::class); 22 | $session = $container->get(SessionInterface::class); 23 | return new TwigAdapter($config, $flash, $session); 24 | }); 25 | 26 | $container->set('db', function () use ($container) { 27 | $dbConfig = $container->get('config')['database']; 28 | try { 29 | return new PDO( 30 | sprintf('mysql:host=%s;dbname=%s', $dbConfig['host'], $dbConfig['dbname']), 31 | $dbConfig['username'], 32 | $dbConfig['password'], 33 | [ 34 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, 35 | PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, 36 | PDO::ATTR_EMULATE_PREPARES => false 37 | ] 38 | ); 39 | 40 | } catch (PDOException $e) { 41 | print "Database Error: " . $e->getMessage(); 42 | die; 43 | } 44 | }); 45 | -------------------------------------------------------------------------------- /config/middleware.php: -------------------------------------------------------------------------------- 1 | addBodyParsingMiddleware(); 12 | $app->addRoutingMiddleware(); 13 | $app->add(SessionMiddleware::class); 14 | $app->add(SlimFlashMiddleware::class); 15 | $app->add(TwigMiddleware::createFromContainer($app)); 16 | }; 17 | -------------------------------------------------------------------------------- /config/routes.php: -------------------------------------------------------------------------------- 1 | getContainer()->get('view')); 14 | 15 | $app->get('/{path}', [AccessUrlController::class, 'execute']); 16 | $app->get('/', [HomeController::class, 'execute']); 17 | 18 | $app->group('/api/public', function (RouteCollectorProxy $group) { 19 | $group->post('/shorten', [ShortenUrlController::class, 'execute']); 20 | }); 21 | }; 22 | -------------------------------------------------------------------------------- /db/migrations/20211001205509_url.php: -------------------------------------------------------------------------------- 1 | table('urls'); 24 | $table 25 | ->addColumn('uuid', 'string', [ 26 | 'limit' => 36 27 | ]) 28 | ->addColumn('user_id', 'binary', [ 29 | 'limit' => 16, 30 | 'null' => true 31 | ]) 32 | ->addColumn('long_url', 'text') 33 | ->addColumn('short_url_path', 'string', [ 34 | 'limit' => 15 35 | ]) 36 | ->addColumn('type', 'enum', [ 37 | 'values' => ['RANDOM','CUSTOM'], 38 | 'default' => 'RANDOM' 39 | ]) 40 | ->addColumn('economy_rate', 'decimal', [ 41 | 'precision' => 10, 42 | 'scale' => 2, 43 | 'default' => 0.00 44 | ]) 45 | ->addColumn('meta', 'json', [ 46 | 'null' => true 47 | ]) 48 | ->addColumn('created_at', 'timestamp', [ 49 | 'default' => 'CURRENT_TIMESTAMP' 50 | ]) 51 | ->addIndex(['uuid', 'short_url_path'], [ 52 | 'unique' => true 53 | ]) 54 | ->create(); 55 | 56 | $table->changeColumn('id', 'binary', [ 57 | 'limit' => 16, 58 | 'signed' => false 59 | ]) 60 | ->update(); 61 | } 62 | 63 | public function down(): void 64 | { 65 | $this->table('urls')->drop()->save(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /db/migrations/20211001205541_url_log.php: -------------------------------------------------------------------------------- 1 | table('urls_logs'); 23 | $table 24 | ->addColumn('uuid', 'string', [ 25 | 'limit' => 36 26 | ]) 27 | ->addColumn('url_id', 'binary', [ 28 | 'limit' => 16 29 | ]) 30 | ->addColumn('meta', 'json', [ 31 | 'null' => true 32 | ]) 33 | ->addColumn('created_at', 'timestamp', [ 34 | 'default' => 'CURRENT_TIMESTAMP' 35 | ]) 36 | ->addIndex(['uuid'], [ 37 | 'unique' => true 38 | ]) 39 | ->create(); 40 | 41 | $table->changeColumn('id', 'binary', [ 42 | 'limit' => 16, 43 | 'signed' => false 44 | ]) 45 | ->update(); 46 | 47 | $table->addForeignKey('url_id', 'urls', ['id'], [ 48 | 'delete' => 'CASCADE', 49 | 'update' => 'CASCADE' 50 | ]) 51 | ->update(); 52 | } 53 | 54 | public function down(): void 55 | { 56 | $this->table('urls_logs')->drop()->save(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /db/migrations/20211015134231_bin_to_uuid.php: -------------------------------------------------------------------------------- 1 | execute($sql); 36 | } 37 | 38 | public function down(): void 39 | { 40 | $this->execute("DROP FUNCTION IF EXISTS BIN_TO_UUID"); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /db/migrations/20211015140735_uuid_to_bin.php: -------------------------------------------------------------------------------- 1 | execute("CREATE DEFINER=`smll_main`@`%.%.%.%` 22 | FUNCTION UUID_TO_BIN(uuid CHAR(36)) RETURNS binary(16) 23 | RETURN UNHEX(REPLACE(uuid, '-', ''));"); 24 | } 25 | 26 | public function down(): void 27 | { 28 | $this->execute("DROP FUNCTION IF EXISTS UUID_TO_BIN"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.5' 2 | services: 3 | app: 4 | container_name: ${APP_NAME}-app 5 | image: dersonsena/php-8.0 6 | command: php -S 0.0.0.0:80 -t /usr/src/app/public_html 7 | build: 8 | context: . 9 | dockerfile: Dockerfile 10 | volumes: 11 | - ./:/usr/src/app 12 | ports: 13 | - '${DOCKER_APP_PORT}:80' 14 | networks: 15 | - smallish 16 | depends_on: 17 | - db 18 | 19 | db: 20 | image: mysql:5.7 21 | container_name: ${APP_NAME}-db 22 | command: --default-authentication-plugin=mysql_native_password --explicit_defaults_for_timestamp=1 23 | restart: always 24 | ports: 25 | - "${DOCKER_MYSQL_PORT}:3306" 26 | environment: 27 | MYSQL_ROOT_PASSWORD: ${DB_PASSWORD} 28 | MYSQL_DATABASE: ${DB_DATABASE} 29 | networks: 30 | - smallish 31 | volumes: 32 | - ./.docker/mysql/data:/var/lib/mysql 33 | 34 | networks: 35 | smallish: 36 | driver: bridge 37 | -------------------------------------------------------------------------------- /docs/smallish-screen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dersonsena/small-sh/bfb1596789ac6966318f47b1d9f0bbde0e49545a/docs/smallish-screen.png -------------------------------------------------------------------------------- /phinx.php: -------------------------------------------------------------------------------- 1 | load(); 5 | 6 | return 7 | [ 8 | 'paths' => [ 9 | 'migrations' => '%%PHINX_CONFIG_DIR%%/db/migrations', 10 | 'seeds' => '%%PHINX_CONFIG_DIR%%/db/seeds' 11 | ], 12 | 'environments' => [ 13 | 'default_migration_table' => 'phinxlog', 14 | 'default_environment' => 'development', 15 | 'production' => [ 16 | 'adapter' => 'mysql', 17 | 'host' => $_ENV['DB_HOST'], 18 | 'name' => $_ENV['DB_DATABASE'], 19 | 'user' => $_ENV['DB_USER'], 20 | 'pass' => $_ENV['DB_PASSWORD'], 21 | 'port' => $_ENV['DB_PORT'], 22 | 'charset' => $_ENV['DB_CHARSET'], 23 | ], 24 | 'development' => [ 25 | 'adapter' => 'mysql', 26 | 'host' => $_ENV['DB_HOST'], 27 | 'name' => $_ENV['DB_DATABASE'], 28 | 'user' => $_ENV['DB_USER'], 29 | 'pass' => $_ENV['DB_PASSWORD'], 30 | 'port' => $_ENV['DB_PORT'], 31 | 'charset' => $_ENV['DB_CHARSET'], 32 | ], 33 | 'testing' => [ 34 | 'adapter' => 'mysql', 35 | 'host' => $_ENV['DB_HOST'], 36 | 'name' => $_ENV['DB_DATABASE'], 37 | 'user' => $_ENV['DB_USER'], 38 | 'pass' => $_ENV['DB_PASSWORD'], 39 | 'port' => $_ENV['DB_PORT'], 40 | 'charset' => $_ENV['DB_CHARSET'], 41 | ] 42 | ], 43 | 'version_order' => 'creation' 44 | ]; 45 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | Smallish Standard 8 | 9 | 10 | ./src 11 | 12 | */vendor/* 13 | */templates/* 14 | */public_html/* 15 | */var/* 16 | 17 | 18 | 19 | 20 | ./vendor/autoload.php 21 | 22 | 23 | 24 | 25 | * 26 | 27 | 28 | -------------------------------------------------------------------------------- /psalm.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /public_html/.htaccess: -------------------------------------------------------------------------------- 1 | RewriteEngine on 2 | RewriteCond %{REQUEST_FILENAME} !-d 3 | RewriteCond %{REQUEST_FILENAME} !-f 4 | RewriteRule . index.php [L] 5 | -------------------------------------------------------------------------------- /public_html/css/style.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | height: 100%; 3 | } 4 | 5 | body { 6 | margin: 0; 7 | background-color: #0b1736; 8 | color: #fff; 9 | font-family: 'Raleway', sans-serif; 10 | } 11 | 12 | /* Chrome, Firefox, Opera, Safari 10.1+ */ 13 | ::placeholder { 14 | color: #d5d5d5 !important; 15 | opacity: 1; /* Firefox */ 16 | } 17 | 18 | ::-webkit-input-placeholder { 19 | color: #d5d5d5 !important; 20 | } 21 | 22 | /* Internet Explorer 10-11 */ 23 | :-ms-input-placeholder { 24 | color: #d5d5d5 !important; 25 | } 26 | 27 | /* Microsoft Edge */ 28 | ::-ms-input-placeholder { 29 | color: #d5d5d5 !important; 30 | } 31 | 32 | /* Small devices (tablets, 768px and up) */ 33 | @media (min-width: 768px) { } 34 | 35 | /* Medium devices (desktops, 992px and up) */ 36 | @media (min-width: 992px) { } 37 | 38 | /* Large devices (large desktops, 1200px and up) */ 39 | @media (min-width: 1200px) { } 40 | 41 | div.home-wrapper { 42 | display: flex; 43 | min-height: 100vh; 44 | justify-content: center; 45 | flex-direction: column; 46 | } 47 | 48 | header.logo h1 { 49 | font-size: 3.5rem; 50 | font-weight: lighter; 51 | letter-spacing: -2.3px; 52 | } 53 | 54 | label#huge-url-label { 55 | font-size: 1.3rem; 56 | text-align: center; 57 | display: block; 58 | } 59 | 60 | input#huge-url { 61 | padding: 1.2rem 1.2rem; 62 | outline: 0; 63 | border-radius: 0.9rem; 64 | } 65 | 66 | input#huge-url:disabled { 67 | background-color: #919191; 68 | opacity: .7; 69 | } 70 | 71 | button.btn-shorten { 72 | padding: .7em; 73 | font-size: 1.5rem; 74 | border-radius: 0.9rem; 75 | } 76 | 77 | div.statistics { 78 | text-align: center; 79 | margin-top: 2em; 80 | } 81 | 82 | div.statistics i { 83 | color: red; 84 | font-size: 1.3em; 85 | } 86 | 87 | div.shortened-urls { 88 | display: none; 89 | color: #333; 90 | border-radius: 0.9rem; 91 | background: #fff; 92 | border: 1px solid #ccc; 93 | padding: 0.3em 0.8em; 94 | margin-top: 1em; 95 | text-align: left; 96 | } 97 | 98 | div.shortened-urls ul { 99 | list-style: none; 100 | margin: 0; 101 | padding: 0; 102 | } 103 | 104 | div.shortened-urls ul li { 105 | padding: 0 0 1.2em 0; 106 | border-bottom: 1px solid #ddd; 107 | } 108 | 109 | div.shortened-urls ul li:last-child { 110 | border-bottom: none; 111 | } 112 | 113 | div.shortened-urls ul li div.long-url { 114 | padding: .5em 0; 115 | } 116 | 117 | div.shortened-urls ul li div.short-url { 118 | } 119 | 120 | div.shortened-urls ul li div.short-url button { 121 | font-size: 1.2em; 122 | padding: 0.6em 0; 123 | } 124 | 125 | div.shortened-urls ul li div.short-url .link { 126 | padding-bottom: .6em; 127 | } 128 | 129 | button.btn-toggle-history span { 130 | margin-left: .5em; 131 | } 132 | 133 | button.btn-shorten span { 134 | margin-left: .3em; 135 | } 136 | 137 | div.shortened-url-result { 138 | display: none; 139 | flex-direction: column; 140 | align-items: center; 141 | margin-top: .8em; 142 | } 143 | 144 | div.shortened-url-result button.copy-button { 145 | font-size: 1.6em; 146 | padding: 1.175rem 3.45rem; 147 | margin-top: .4em; 148 | margin-bottom: 1.2em; 149 | width: 100%; 150 | } 151 | 152 | div.shortened-url-result a span.url-text { 153 | font-size: 1.7em; 154 | } 155 | 156 | div.shortened-url-result span.badge { 157 | position: absolute; 158 | margin: -1.6em 1em 1em -3.1em; 159 | font-size: 0.9em; 160 | } -------------------------------------------------------------------------------- /public_html/images/meta-image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dersonsena/small-sh/bfb1596789ac6966318f47b1d9f0bbde0e49545a/public_html/images/meta-image.png -------------------------------------------------------------------------------- /public_html/index.php: -------------------------------------------------------------------------------- 1 | load(); 11 | 12 | defined('DS') or define('DS', DIRECTORY_SEPARATOR); 13 | defined('ROOT_PATH') or define('ROOT_PATH', dirname(__DIR__)); 14 | defined('CONFIG_PATH') or define('CONFIG_PATH', ROOT_PATH . DS . 'config'); 15 | defined('APP_PATH') or define('APP_PATH', ROOT_PATH . DS . 'src'); 16 | defined('APP_ENV') or define('APP_ENV', $_ENV['APP_ENV']); 17 | defined('APP_IS_PRODUCTION') or define('APP_IS_PRODUCTION', APP_ENV === 'production'); 18 | 19 | date_default_timezone_set($_ENV['APP_DEFAULT_TIMEZONE']); 20 | locale_set_default($_ENV['APP_DEFAULT_LOCALE']); 21 | 22 | require_once CONFIG_PATH . '/dic.php'; 23 | 24 | AppFactory::setContainer($container); 25 | $app = AppFactory::create(); 26 | 27 | // Register middleware 28 | $middleware = require CONFIG_PATH . '/middleware.php'; 29 | $middleware($app); 30 | 31 | // Register routes 32 | $routes = require CONFIG_PATH . '/routes.php'; 33 | $routes($app); 34 | 35 | // Create Request object from globals 36 | $serverRequestCreator = ServerRequestCreatorFactory::create(); 37 | $request = $serverRequestCreator->createServerRequestFromGlobals(); 38 | 39 | // Add Error Middleware 40 | $displayErrorDetails = $container->get('config')['displayErrorDetails']; 41 | $errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false); 42 | 43 | $app->run(); 44 | -------------------------------------------------------------------------------- /public_html/js/script.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | let urlHistory = window.localStorage.getItem('url_history'); 3 | 4 | if (urlHistory) { 5 | urlHistory = JSON.parse(urlHistory); 6 | 7 | urlHistory = urlHistory.map(row => { 8 | if (!row.hasOwnProperty('huge')) return row; 9 | return { 10 | longUrl: row.huge, 11 | shortenedUrl: row.shortened, 12 | createdAt: row.created_at, 13 | economyRate: row.economyRate, 14 | }; 15 | }); 16 | 17 | window.localStorage.setItem('url_history', JSON.stringify(urlHistory)); 18 | 19 | for (let index in urlHistory) { 20 | if (index === '5') break; 21 | $('div.shortened-urls ul').append(getHistoryItemTemplate(urlHistory[index])); 22 | } 23 | } 24 | 25 | $('button.btn-toggle-history').on('click', function () { 26 | const $button = $('button.btn-toggle-history'); 27 | $('.shortened-urls').fadeToggle('fast', 'linear', function () { 28 | if ($(this).css('display') === 'block') { 29 | $button.find('span').html('Esconder meu histórico') 30 | } else { 31 | $button.find('span').html('Ver meu histórico') 32 | } 33 | }); 34 | }); 35 | 36 | $('button.copy-button').on('click', function () { 37 | const $btn = $(this); 38 | navigator.clipboard.writeText($btn.attr('data-url')); 39 | 40 | $btn.removeClass('btn-light') 41 | $btn.addClass('btn-success') 42 | $btn.html(' Copiado!') 43 | setTimeout(function () { 44 | $btn.removeClass('btn-success') 45 | $btn.addClass('btn-light') 46 | $btn.html(' Copiar') 47 | }, 3000) 48 | }); 49 | 50 | $('button.btn-shorten').on('click', function (e) { 51 | e.preventDefault(); 52 | const $inputUrl = $('input#huge-url'); 53 | const $btnShorten = $(this); 54 | 55 | if ($inputUrl.val() === '') { 56 | alert('Informe sua URL para poder encurtar.') 57 | $inputUrl.select(); 58 | return false; 59 | } 60 | 61 | const regex = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g; 62 | 63 | if (!regex.test($inputUrl.val())) { 64 | alert('Informe uma URL válida para poder encurtar.') 65 | $inputUrl.select(); 66 | return false; 67 | } 68 | 69 | const originalContent = $btnShorten.html(); 70 | 71 | $.ajax({ 72 | url: `${baseUrl}/api/public/shorten`, 73 | type: 'post', 74 | data: { long_url : $inputUrl.val() }, 75 | beforeSend : function() { 76 | $inputUrl.prop('disabled', true); 77 | $btnShorten.prop('disabled', true); 78 | const $span = $('').html('Preparando sua URL...'); 79 | $btnShorten.empty().append($span); 80 | } 81 | }).done(function(payload) { 82 | const urlHistory = window.localStorage.getItem('url_history'); 83 | const currentHistory = urlHistory ? JSON.parse(urlHistory) : []; 84 | currentHistory.push(payload.data); 85 | currentHistory.sort(function (a, b) { 86 | return new Date(b.created_at) - new Date(a.created_at); 87 | }); 88 | 89 | window.localStorage.setItem('url_history', JSON.stringify(currentHistory)); 90 | 91 | $('div.shortened-urls ul').prepend(getHistoryItemTemplate(payload.data)); 92 | 93 | $btnShorten.html(originalContent); 94 | $btnShorten.removeAttr('disabled'); 95 | $inputUrl.removeAttr('disabled'); 96 | $('form#form-shorten').hide(); 97 | $('div.history-wrapper').hide(); 98 | 99 | const $divResult = $('div.shortened-url-result'); 100 | $divResult.css('display', 'flex'); 101 | $divResult.find('a').attr('href', payload.data.shortenedUrl); 102 | $divResult.find('a span.url-text').html(payload.data.shortenedUrl); 103 | $divResult.find('a span.badge').html(`-${payload.data.economyRate}%`); 104 | $divResult.find('button').attr('data-url', payload.data.shortenedUrl); 105 | }).fail(function(jqXHR, textStatus, msg) { 106 | if (jqXHR.status === 400) { 107 | const payload = jqXHR.responseJSON; 108 | let message = ''; 109 | switch (payload.data.longUrl) { 110 | case 'invalid-url': 111 | message = 'Insira ua URL válida com "http://" ou "https://" para poder encurtar.'; 112 | break; 113 | case 'empty-value': 114 | message = 'Url longa não pode ser vazia.'; 115 | break; 116 | } 117 | alert(message); 118 | $inputUrl.select(); 119 | } 120 | 121 | if (jqXHR.status === 500) { 122 | alert('Ops, ocorreu algum problema pra gerar sua URL. Por favor, tenta novamente.'); 123 | } 124 | 125 | $btnShorten.html(originalContent); 126 | $btnShorten.removeAttr('disabled'); 127 | $inputUrl.removeAttr('disabled'); 128 | }); 129 | }); 130 | 131 | $('button.new-url').on('click', function () { 132 | $('form#form-shorten').show(); 133 | $('div.history-wrapper').show(); 134 | const $divResult = $('div.shortened-url-result'); 135 | $divResult.css('display', 'none'); 136 | $divResult.find('a').attr('href', '#'); 137 | $divResult.find('button').attr('data-url', ''); 138 | 139 | const $input = $('input#huge-url'); 140 | $input.val(''); 141 | $input.select(); 142 | }); 143 | }); 144 | 145 | function getHistoryItemTemplate(data) { 146 | return ` 147 |
  • 148 |
    ${data.longUrl.substring(0, 38)}...
    149 |
    150 | 155 |
    156 |
    157 | 160 |
    161 |
    162 |
    163 |
  • 164 | `; 165 | } -------------------------------------------------------------------------------- /src/Adapter/Controllers/AccessUrlController.php: -------------------------------------------------------------------------------- 1 | longUrlRepo->getUrlByPath($this->args['path']); 22 | 23 | if (is_null($url)) { 24 | return $this->render('notfound'); 25 | } 26 | 27 | $this->longUrlRepo->registerAccess($url, [ 28 | 'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'], 29 | 'REMOTE_PORT' => $_SERVER['REMOTE_PORT'], 30 | 'SERVER_PROTOCOL' => $_SERVER['SERVER_PROTOCOL'], 31 | 'SERVER_NAME' => $_SERVER['SERVER_NAME'], 32 | 'REQUEST_URI' => $_SERVER['REQUEST_URI'], 33 | 'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'], 34 | 'HTTP_HOST' => $_SERVER['HTTP_HOST'], 35 | 'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'], 36 | 'HTTP_REFERER' => $_SERVER['HTTP_REFERER'] ?? '', 37 | ]); 38 | 39 | return $this->redirect($url->longUrl->value()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Adapter/Controllers/HomeController.php: -------------------------------------------------------------------------------- 1 | longUrlRepo->countUrlsAndClicks(); 22 | return $this->render('index', $rows); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Adapter/Controllers/ShortenUrlController.php: -------------------------------------------------------------------------------- 1 | config = $container->get('config'); 22 | $this->useCase = $container->get(ShortenUrl::class); 23 | } 24 | 25 | public function handle(Request $request): array 26 | { 27 | $contents = $request->getParsedBody(); 28 | 29 | $result = $this->useCase->execute(InputData::create([ 30 | 'longUrl' => $contents['long_url'] ?? '', 31 | 'type' => LongUrlType::TYPE_RANDOM, 32 | 'baseUrl' => $this->config['baseUrl'], 33 | ])); 34 | 35 | return $result->values(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Adapter/Repository/Database/DbLongUrlRepository.php: -------------------------------------------------------------------------------- 1 | orm); 26 | } 27 | 28 | public function shortLongUrl(LongUrl $url): LongUrl 29 | { 30 | $url->set('id', $this->uuidGenerator->create()); 31 | 32 | $this->create([ 33 | 'id' => $this->uuidGenerator->toBytes($url->id), 34 | 'uuid' => $url->id, 35 | 'long_url' => $url->longUrl->value(), 36 | 'short_url_path' => $url->getShortUrlPath(), 37 | 'type' => $url->type->value(), 38 | 'economy_rate' => $url->calculateEconomyRate(), 39 | 'created_at' => $url->createdAt->format('Y-m-d H:i:s') 40 | ]); 41 | 42 | return $url; 43 | } 44 | 45 | public function getUrlByPath(string $path): ?LongUrl 46 | { 47 | $errors = []; 48 | 49 | if (empty($path)) { 50 | $errors['path'][] = 'empty-path'; 51 | } 52 | 53 | if (!empty($errors)) { 54 | throw new ValidationException($errors); 55 | } 56 | 57 | $urlRecord = $this->fetchOne(['short_url_path' => $path]); 58 | 59 | if (is_null($urlRecord)) { 60 | return null; 61 | } 62 | 63 | return LongUrl::create([ 64 | 'id' => $urlRecord['uuid'], 65 | 'longUrl' => $urlRecord['long_url'], 66 | 'shortUrl' => $this->baseUrl . '/' . $urlRecord['short_url_path'], 67 | 'baseUrlToShortUrl' => $this->baseUrl, 68 | 'type' => $urlRecord['type'], 69 | 'createdAt' => $urlRecord['created_at'] 70 | ]); 71 | } 72 | 73 | public function registerAccess(LongUrl $url, array $metaInfo = []) 74 | { 75 | $uuid = $this->uuidGenerator->create(); 76 | 77 | $this->orm->create('urls_logs', [ 78 | 'id' => $this->uuidGenerator->toBytes($uuid), 79 | 'uuid' => $uuid, 80 | 'url_id' => $this->uuidGenerator->toBytes($url->id), 81 | 'created_at' => (new DateTimeImmutable())->format('Y-m-d H:i:s'), 82 | 'meta' => json_encode($metaInfo) 83 | ]); 84 | } 85 | 86 | public function countUrlsAndClicks(): array 87 | { 88 | $sql = " 89 | select count(*) as `total_urls` from `{$this->tableName}` 90 | union all 91 | select count(*) as `total_clicks` from `urls_logs` 92 | "; 93 | 94 | $rows = $this->orm->querySql($sql, [], ['fetchMode' => PDO::FETCH_COLUMN]); 95 | 96 | return [ 97 | 'totalUrls' => ceil($rows[0]), 98 | 'totalClicks' => ceil($rows[1]) 99 | ]; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/Domain/Entity/LongUrl.php: -------------------------------------------------------------------------------- 1 | format(DateTimeInterface::ATOM); 34 | } 35 | 36 | if (!isset($values['shortUrl'])) { 37 | $values['shortUrl'] = $values['baseUrlToShortUrl'] . '/' . self::generatePathToShortUrl(); 38 | } 39 | 40 | return parent::create($values); 41 | } 42 | 43 | protected function setBaseUrlToShortUrl(string $baseUrl) 44 | { 45 | $this->baseUrlToShortUrl = new Url($baseUrl); 46 | } 47 | 48 | protected function setLongUrl(string $longUrl) 49 | { 50 | $this->longUrl = new Url($longUrl); 51 | } 52 | 53 | protected function setShortUrl(string $shortUrl) 54 | { 55 | $this->shortUrl = new Url($shortUrl); 56 | } 57 | 58 | protected function setType(string $type) 59 | { 60 | $this->type = new LongUrlType($type); 61 | } 62 | 63 | protected function setCreatedAt(string $createdAt) 64 | { 65 | $this->createdAt = new DateTimeImmutable($createdAt); 66 | } 67 | 68 | public function calculateEconomyRate(): float 69 | { 70 | return ceil(100 - ((strlen($this->shortUrl->value()) * 100) / strlen($this->longUrl->value()))); 71 | } 72 | 73 | public function getShortUrlPath(): string 74 | { 75 | $urlParts = explode('/', $this->shortUrl->value()); 76 | return end($urlParts); 77 | } 78 | 79 | public function renewShortUrlPath(): void 80 | { 81 | $this->shortUrl = new Url($this->baseUrlToShortUrl . '/' . self::generatePathToShortUrl()); 82 | } 83 | 84 | public static function generatePathToShortUrl(): string 85 | { 86 | return substr(sha1(uniqid((string)rand(), true)), 0, self::SHORT_URL_PATH_LENGTH); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/Domain/Exceptions/InvalidLongUrl.php: -------------------------------------------------------------------------------- 1 | 'invalid-type'], "The given URL Type '{$giveType}' is invalid"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Domain/Repository/LongUrlRepository.php: -------------------------------------------------------------------------------- 1 | longUrl)) { 24 | $errors['longUrl'][] = 'empty-value'; 25 | } 26 | 27 | if (!filter_var($input->longUrl, FILTER_VALIDATE_URL)) { 28 | $errors['longUrl'][] = 'invalid-url'; 29 | } 30 | 31 | if (!empty($errors)) { 32 | throw new ValidationException($errors); 33 | } 34 | 35 | while (true) { 36 | $longUrl = LongUrl::create([ 37 | 'longUrl' => $input->longUrl, 38 | 'baseUrlToShortUrl' => $input->baseUrl, 39 | 'type' => $input->type 40 | ]); 41 | 42 | if ($this->longUrlRepo->getUrlByPath($longUrl->getShortUrlPath())) { 43 | $longUrl->renewShortUrlPath(); 44 | continue; 45 | } 46 | 47 | break; 48 | } 49 | 50 | $longUrl = $this->longUrlRepo->shortLongUrl($longUrl); 51 | 52 | return OutputData::create([ 53 | 'longUrl' => $longUrl->longUrl->value(), 54 | 'shortenedUrl' => $longUrl->shortUrl->value(), 55 | 'economyRate' => $longUrl->calculateEconomyRate(), 56 | 'createdAt' => $longUrl->createdAt->format(DateTimeInterface::ATOM), 57 | ]); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Domain/ValueObject/LongUrlType.php: -------------------------------------------------------------------------------- 1 | type = $type; 27 | } 28 | 29 | public function value(): mixed 30 | { 31 | return $this->type; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Contracts/DatabaseOrm.php: -------------------------------------------------------------------------------- 1 | 10 | */ 11 | interface Dto 12 | { 13 | /** 14 | * Associative array such as `'property' => 'value'` with all boundary values 15 | * @return array 16 | */ 17 | public function values(): array; 18 | 19 | /** 20 | * Get a boundary value by property 21 | * @param string $property 22 | * @return mixed 23 | */ 24 | public function get(string $property); 25 | } 26 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Contracts/TemplateEngine.php: -------------------------------------------------------------------------------- 1 | request->getMethod() === 'POST'; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Controller/RestController.php: -------------------------------------------------------------------------------- 1 | request = $request; 25 | $this->response = $response; 26 | $this->args = $args; 27 | 28 | $this->parseBody(); 29 | 30 | try { 31 | return $this->answerSuccess($this->handle($this->request)); 32 | } catch (ValidationException $e) { 33 | $meta = []; 34 | 35 | if (!APP_IS_PRODUCTION) { 36 | $meta = [ 37 | 'name' => $e->getName(), 38 | 'code' => $e->getCode(), 39 | 'message' => $e->getMessage(), 40 | 'file' => $e->getFile() . ':' . $e->getLine(), 41 | 'stackTrace' => $e->getTraceAsString() 42 | ]; 43 | } 44 | 45 | return $this->answerFail($e->details(), $meta); 46 | } catch (RuntimeException $e) { 47 | $meta = []; 48 | 49 | if (!APP_IS_PRODUCTION) { 50 | $meta = [ 51 | 'name' => $e->getName(), 52 | 'code' => $e->getCode(), 53 | 'file' => $e->getFile() . ':' . $e->getLine(), 54 | 'stackTrace' => $e->getTraceAsString() 55 | ]; 56 | } 57 | 58 | return $this->answerError($e->getMessage(), $meta); 59 | } 60 | } 61 | 62 | private function parseBody(): void 63 | { 64 | $contentType = $this->request->getHeaderLine('Content-Type'); 65 | 66 | if (!strstr($contentType, 'application/json')) { 67 | return; 68 | } 69 | 70 | $contents = json_decode(file_get_contents('php://input'), true); 71 | 72 | if (json_last_error() !== JSON_ERROR_NONE) { 73 | return; 74 | } 75 | 76 | $this->request->withParsedBody($contents); 77 | } 78 | 79 | private function answerSuccess(array $data, int $statusCode = 200, array $meta = []): Response 80 | { 81 | $newResponse = $this->response 82 | ->withHeader('Content-Type', 'application/json') 83 | ->withStatus($statusCode); 84 | 85 | $newResponse->getBody()->write(json_encode([ 86 | 'status' => 'success', 87 | 'data' => $data, 88 | 'meta' => $meta 89 | ])); 90 | 91 | return $newResponse; 92 | } 93 | 94 | private function answerFail(array $data, array $meta = []): Response 95 | { 96 | $newResponse = $this->response 97 | ->withHeader('Content-Type', 'application/json') 98 | ->withStatus(400); 99 | 100 | $newResponse->getBody()->write(json_encode([ 101 | 'status' => 'fail', 102 | 'data' => $data, 103 | 'meta' => $meta 104 | ])); 105 | 106 | return $newResponse; 107 | } 108 | 109 | private function answerError(string $message, $meta = []): Response 110 | { 111 | $newResponse = $this->response 112 | ->withHeader('Content-Type', 'application/json') 113 | ->withStatus(500); 114 | 115 | $newResponse->getBody()->write(json_encode([ 116 | 'status' => 'error', 117 | 'message' => $message, 118 | 'meta' => $meta 119 | ])); 120 | 121 | return $newResponse; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Controller/TemplateController.php: -------------------------------------------------------------------------------- 1 | request = $request; 30 | $this->response = $response; 31 | $this->args = $args; 32 | $this->view = TemplateEngineFactory::get(); 33 | 34 | try { 35 | return $this->handle($this->request) 36 | ->withHeader('Content-Type', 'text/html') 37 | ->withStatus(200); 38 | } catch (ValidationException | RuntimeException $e) { 39 | return $this->answerError($e); 40 | } 41 | } 42 | 43 | private function answerError(Error $e): Response 44 | { 45 | $newResponse = $this->render('error', [ 46 | 'name' => $e->getName(), 47 | 'message' => $e->getMessage(), 48 | 'details' => $e->details(), 49 | 'stackTrace' => $e->getTraceAsString() 50 | ]) 51 | ->withHeader('Content-Type', 'text/html') 52 | ->withStatus(500); 53 | 54 | return $newResponse; 55 | } 56 | 57 | /** 58 | * @param string $templatePath 59 | * @param array $params 60 | * @return Response 61 | */ 62 | protected function render(string $templatePath, array $params = []): Response 63 | { 64 | return $this->view->render($this->response, $templatePath, $params); 65 | } 66 | 67 | /** 68 | * @param string $url 69 | * @return Response 70 | */ 71 | protected function redirect(string $url): Response 72 | { 73 | return $this->response 74 | ->withStatus(302) 75 | ->withHeader('Location', $url); 76 | } 77 | 78 | /** 79 | * @return Response 80 | */ 81 | protected function refresh(): Response 82 | { 83 | return $this->redirect($_SERVER['HTTP_REFERER']); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Controller/TemplateEngineFactory.php: -------------------------------------------------------------------------------- 1 | 13 | */ 14 | abstract class DtoBase implements Dto 15 | { 16 | private array $values = []; 17 | 18 | /** 19 | * Boundary constructor. 20 | * @param array $values 21 | * @throws InvalidDtoParam 22 | */ 23 | final private function __construct(array $values) 24 | { 25 | foreach ($values as $key => $value) { 26 | if (mb_strstr($key, '_') !== false) { 27 | $key = lcfirst(str_replace('_', '', ucwords($key, '_'))); 28 | } 29 | 30 | if (!property_exists($this, $key)) { 31 | throw InvalidDtoParam::forDynamicParam(get_class(), $key); 32 | } 33 | 34 | $this->{$key} = $value; 35 | $this->values[$key] = $this->get($key); 36 | } 37 | } 38 | 39 | /** 40 | * Static method to create a Boundary (Input or Output) 41 | * @param array $values Associative array such as `'property' => 'value'` 42 | * @throws InvalidDtoParam 43 | */ 44 | public static function create(array $values): static 45 | { 46 | return new static($values); 47 | } 48 | 49 | /** 50 | * {@inheritdoc} 51 | */ 52 | public function values(): array 53 | { 54 | return $this->values; 55 | } 56 | 57 | /** 58 | * {@inheritdoc} 59 | * @throws InvalidDtoParam 60 | */ 61 | public function get(string $property) 62 | { 63 | return $this->__get($property); 64 | } 65 | 66 | /** 67 | * Magic getter method to get a Boundary property value 68 | * @param string $name 69 | * @return mixed 70 | * @throws InvalidDtoParam 71 | */ 72 | public function __get(string $name) 73 | { 74 | $getter = "get" . ucfirst($name); 75 | 76 | if (method_exists($this, $getter)) { 77 | return $this->{$getter}(); 78 | } 79 | 80 | if (!property_exists($this, $name)) { 81 | throw InvalidDtoParam::forDynamicParam(get_class(), $name); 82 | } 83 | 84 | return $this->{$name}; 85 | } 86 | 87 | /** 88 | * @param string $name 89 | * @param mixed $value 90 | * @throws InvalidDtoParam 91 | */ 92 | public function __set(string $name, mixed $value) 93 | { 94 | throw InvalidDtoParam::forReadonlyProperty(get_class(), $name); 95 | } 96 | 97 | public function __isset($name): bool 98 | { 99 | return property_exists($this, $name); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Exception/InvalidDtoParam.php: -------------------------------------------------------------------------------- 1 | withAttribute('session', $_SESSION); 22 | } 23 | 24 | return $handler->handle($request); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Middleware/SlimFlashMiddleware.php: -------------------------------------------------------------------------------- 1 | session = $session; 20 | $this->flash = $flash; 21 | } 22 | 23 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 24 | { 25 | $allSession = $this->session->all(); 26 | $this->flash->__construct($allSession); 27 | return $handler->handle($request); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Shared/Adapter/Middleware/TwigMiddleware.php: -------------------------------------------------------------------------------- 1 | getContainer(); 17 | 18 | if ($container === null) { 19 | throw new RuntimeException('The app does not have a container.'); 20 | } 21 | 22 | if (!$container->has($containerKey)) { 23 | throw new RuntimeException( 24 | "The specified container key does not exist: $containerKey" 25 | ); 26 | } 27 | 28 | /** @var TwigAdapter $twigAdapter */ 29 | $twigAdapter = $container->get($containerKey); 30 | 31 | if (!($twigAdapter->getTwig() instanceof Twig)) { 32 | throw new RuntimeException( 33 | "Twig instance could not be resolved via container key: $containerKey" 34 | ); 35 | } 36 | 37 | return new self( 38 | $twigAdapter->getTwig(), 39 | $app->getRouteCollector()->getRouteParser(), 40 | $app->getBasePath() 41 | ); 42 | } 43 | } -------------------------------------------------------------------------------- /src/Shared/Adapter/RepositoryBase.php: -------------------------------------------------------------------------------- 1 | orm->read($this->tableName, [$this->pkColumn => $id]); 23 | } 24 | 25 | public function fetchOne(array $conditions, array $options = []): array|null 26 | { 27 | return $this->orm->read($this->tableName, $conditions, $options); 28 | } 29 | 30 | public function fetchAll(array $conditions, array $options = []): array 31 | { 32 | return $this->orm->search($this->tableName, $conditions, $options); 33 | } 34 | 35 | public function create(array $values): int|string 36 | { 37 | return $this->orm->create($this->tableName, $values); 38 | } 39 | 40 | public function update(array $values, array $conditions): bool 41 | { 42 | return $this->orm->update($this->tableName, $values, $conditions); 43 | } 44 | 45 | public function delete(array $conditions): bool 46 | { 47 | return $this->orm->delete($this->tableName, $conditions); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Shared/Domain/Contracts/Entity.php: -------------------------------------------------------------------------------- 1 | 'value'` 18 | * @return void 19 | */ 20 | public function fill(array $values): void; 21 | 22 | /** 23 | * Method that contains the property setter logic 24 | * @param string $property Object property name 25 | * @param mixed $value Value to be inserted in property 26 | * @return Entity 27 | */ 28 | public function set(string $property, $value): Entity; 29 | 30 | /** 31 | * Method that contains the property getter logic 32 | * @param string $property Object property name 33 | * @return mixed 34 | */ 35 | public function get(string $property); 36 | 37 | /** 38 | * Output an array based on entity properties 39 | * @param bool $toSnakeCase 40 | * @return array 41 | */ 42 | public function toArray(bool $toSnakeCase = false): array; 43 | } 44 | -------------------------------------------------------------------------------- /src/Shared/Domain/Contracts/Repository.php: -------------------------------------------------------------------------------- 1 | 17 | * 18 | * @property-read int|string $id 19 | */ 20 | abstract class EntityBase implements Entity 21 | { 22 | protected string | int | null $id = null; 23 | 24 | /** 25 | * Entity constructor. 26 | * @param array $values 27 | * @throws InvalidEntityException 28 | */ 29 | final private function __construct(array $values) 30 | { 31 | $this->fill($values); 32 | } 33 | 34 | /** 35 | * Static method to create an Entity 36 | * @param array $values 37 | * @return EntityBase 38 | * @throws InvalidEntityException 39 | */ 40 | public static function create(array $values): self 41 | { 42 | return new static($values); 43 | } 44 | 45 | /** 46 | * @inheritDoc 47 | */ 48 | public function getId() 49 | { 50 | return $this->id; 51 | } 52 | 53 | /** 54 | * @inheritDoc 55 | * @throws InvalidEntityException 56 | */ 57 | public function fill(array $values): void 58 | { 59 | foreach ($values as $attribute => $value) { 60 | $this->set($attribute, $value); 61 | } 62 | } 63 | 64 | /** 65 | * @inheritDoc 66 | * @throws InvalidEntityException 67 | */ 68 | public function set(string $property, $value): Entity 69 | { 70 | if (mb_strstr($property, '_') !== false) { 71 | $property = lcfirst(str_replace('_', '', ucwords($property, '_'))); 72 | } 73 | 74 | $setter = 'set' . str_replace('_', '', ucwords($property, '_')); 75 | 76 | if (method_exists($this, $setter)) { 77 | $this->{$setter}($value); 78 | return $this; 79 | } 80 | 81 | if (!property_exists($this, $property)) { 82 | $className = get_class(); 83 | throw InvalidEntityException::readonlyProperty($className, $property); 84 | } 85 | 86 | $this->{$property} = $value; 87 | return $this; 88 | } 89 | 90 | /** 91 | * @inheritDoc 92 | */ 93 | public function get(string $property) 94 | { 95 | return $this->{$property}; 96 | } 97 | 98 | /** 99 | * @inheritDoc 100 | * @throws ReflectionException 101 | */ 102 | public function toArray(bool $toSnakeCase = false): array 103 | { 104 | $props = []; 105 | $propertyList = get_object_vars($this); 106 | 107 | /** @var int|string|object $value */ 108 | foreach ($propertyList as $prop => $value) { 109 | if ($value instanceof DateTimeInterface) { 110 | $propertyList[$prop] = $value->format(DATE_ATOM); 111 | continue; 112 | } 113 | 114 | if (is_object($value)) { 115 | $reflectObject = new ReflectionClass(get_class($value)); 116 | $properties = $reflectObject->getProperties(); 117 | $propertyList[$prop] = []; 118 | 119 | foreach ($properties as $property) { 120 | $property->setAccessible(true); 121 | $propertyList[$prop][$property->getName()] = $property->getValue($value); 122 | } 123 | } 124 | } 125 | 126 | $propertyList = json_decode(json_encode($propertyList), true); 127 | 128 | foreach ($propertyList as $name => $value) { 129 | if ($toSnakeCase) { 130 | $name = mb_strtolower(preg_replace('/(?{$getter}(); 151 | } 152 | 153 | if (!property_exists($this, $name)) { 154 | $className = get_class(); 155 | throw InvalidEntityException::propertyDoesNotExists($className, $name); 156 | } 157 | 158 | return $this->{$name}; 159 | } 160 | 161 | /** 162 | * @param string $name 163 | * @param mixed $value 164 | * @throws InvalidEntityException 165 | */ 166 | public function __set(string $name, mixed $value) 167 | { 168 | $className = get_class(); 169 | throw InvalidEntityException::readonlyProperty($className, $name); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/Shared/Domain/Exceptions/InvalidEntityException.php: -------------------------------------------------------------------------------- 1 | value(); 19 | } 20 | 21 | /** 22 | * @inheritDoc 23 | */ 24 | public function isEqualsTo(ValueObject $valueObject): bool 25 | { 26 | return $this->objectHash() === $valueObject->objectHash(); 27 | } 28 | 29 | /** 30 | * @inheritDoc 31 | * @throws ReflectionException 32 | */ 33 | public function objectHash(): string 34 | { 35 | $reflectObject = new ReflectionClass(get_class($this)); 36 | $props = $reflectObject->getProperties(); 37 | $value = ''; 38 | 39 | foreach ($props as $prop) { 40 | $prop->setAccessible(true); 41 | $value .= $prop->getValue($this); 42 | } 43 | 44 | return md5($value); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Shared/Domain/ValueObjects/Url.php: -------------------------------------------------------------------------------- 1 | url = $url; 28 | } 29 | 30 | public function value(): mixed 31 | { 32 | return $this->url; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Shared/Exception/Error.php: -------------------------------------------------------------------------------- 1 | details = $details; 18 | $this->code = $this->errorCode ?? $code; 19 | } 20 | 21 | public function details(): array 22 | { 23 | return $this->details; 24 | } 25 | 26 | public function getName(): string 27 | { 28 | return 'Generic Error'; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Shared/Exception/RuntimeException.php: -------------------------------------------------------------------------------- 1 | ':' . $columnName, $columns); 21 | $columns = array_map(fn($columnName) => '`' . $columnName . '`', $columns); 22 | $sql = sprintf( 23 | 'INSERT INTO `%s` (%s) VALUES (%s)', 24 | $tableName, 25 | implode(',', $columns), 26 | implode(',', $columnsVars) 27 | ); 28 | $stmt = $this->pdo->prepare($sql); 29 | $stmt->execute($values); 30 | 31 | return $this->pdo->lastInsertId('uuid'); 32 | } 33 | 34 | public function read(string $tableName, array $filters, array $options = []): ?array 35 | { 36 | $columns = '*'; 37 | $clauses = ''; 38 | 39 | if (isset($options['columns'])) { 40 | $columns = array_map(fn ($columnName) => '`' . $columnName . '`', $options['columns']); 41 | $columns = implode(',', $columns); 42 | } 43 | 44 | $filterColumns = array_keys($filters); 45 | $i = 0; 46 | 47 | foreach ($filterColumns as $columnName) { 48 | if ($i === 0) { 49 | $clauses .= "WHERE `{$columnName}` = :{$columnName}"; 50 | } 51 | 52 | if ($i > 0) { 53 | $clauses .= "AND `{$columnName}` = :{$columnName}"; 54 | } 55 | 56 | $i++; 57 | } 58 | 59 | $sql = sprintf("SELECT %s FROM `%s` %s", $columns, $tableName, $clauses); 60 | $stmt = $this->pdo->prepare($sql); 61 | $stmt->execute($filters); 62 | $row = $stmt->fetch(); 63 | 64 | if (!$row) { 65 | return null; 66 | } 67 | 68 | return $row; 69 | } 70 | 71 | public function update(string $tableName, array $values, array $conditions): bool 72 | { 73 | $columns = array_keys($values); 74 | $columnsToUpdate = array_map(fn($columnName) => "`{$columnName}` = :{$columnName}", $columns); 75 | $clauses = []; 76 | 77 | foreach ($conditions as $columnName => $value) { 78 | $values[$columnName] = $value; 79 | $clauses[] = "`{$columnName}` = :{$columnName}"; 80 | } 81 | 82 | $sql = sprintf( 83 | 'UPDATE `%s` SET %s WHERE %s', 84 | $tableName, 85 | implode(', ', $columnsToUpdate), 86 | implode(' AND ', $clauses), 87 | ); 88 | 89 | $stmt = $this->pdo->prepare($sql); 90 | return $stmt->execute($values); 91 | } 92 | 93 | public function delete(string $tableName, array $conditions): bool 94 | { 95 | $values = []; 96 | $clauses = []; 97 | 98 | foreach ($conditions as $columnName => $value) { 99 | $values[$columnName] = $value; 100 | $clauses[] = "`{$columnName}` = :{$columnName}"; 101 | } 102 | 103 | $sql = sprintf('DELETE FROM `%s` WHERE %s', $tableName, implode(' AND ', $clauses)); 104 | $stmt = $this->pdo->prepare($sql); 105 | return $stmt->execute($values); 106 | } 107 | 108 | public function search(string $tableName, array $filters, array $options = []): array 109 | { 110 | return []; 111 | } 112 | 113 | public function persist(string $tableName, array $values): int|string 114 | { 115 | if (isset($values['id']) && !empty($values['id'])) { 116 | $this->update($tableName, $values, ['id' => $values['id']]); 117 | return $values['uuid']; 118 | } 119 | 120 | return $this->create($tableName, $values); 121 | } 122 | 123 | public function querySql(string $sql, array $values = [], array $options = []): array 124 | { 125 | $stmt = $this->pdo->prepare(trim($sql)); 126 | $stmt->execute($values); 127 | $fetchMode = $options['fetchMode'] ?? PDO::FETCH_ASSOC; 128 | return $stmt->fetchAll($fetchMode); 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/Shared/Infra/RamseyUiidAdapter.php: -------------------------------------------------------------------------------- 1 | toString(); 15 | } 16 | 17 | public function toBytes(string $uuid): string 18 | { 19 | return Uuid::fromString($uuid)->getBytes(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Shared/Infra/TwigAdapter.php: -------------------------------------------------------------------------------- 1 | twig = Twig::create( 21 | $config['twig']['templatePath'], 22 | ['cache' => APP_IS_PRODUCTION ? $config['twig']['cachePath'] : false] 23 | ); 24 | 25 | $this->twig->addExtension(new DebugExtension()); 26 | 27 | $this->twig->getEnvironment()->addGlobal('displayErrorDetails', $config['displayErrorDetails']); 28 | $this->twig->getEnvironment()->addGlobal('baseUrl', $config['baseUrl']); 29 | $this->twig->getEnvironment()->addGlobal('session', $session); 30 | $this->twig->getEnvironment()->addGlobal('flash', $flash); 31 | $this->twig->getEnvironment()->addGlobal('sessionCookieName', $config['session']['name']); 32 | } 33 | 34 | public function getTwig(): Twig 35 | { 36 | return $this->twig; 37 | } 38 | 39 | public function render(Response $response, string $templateFile, array $params = []): Response 40 | { 41 | if (!preg_match("/^.*\.html.twig$/D", $templateFile)) { 42 | $templateFile .= '.html.twig'; 43 | } 44 | 45 | return $this->twig->render($response, $templateFile, $params); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /templates/error.html.twig: -------------------------------------------------------------------------------- 1 | {% extends 'layouts/base.html.twig' %} 2 | 3 | {% block title %}Houve um erro{% endblock %} 4 | 5 | {% block content %} 6 |
    7 | 10 |
    11 |

    Opss... ocorreu algum probleminha durante sua requisição. Por favor, tente novamente.

    12 | Voltar para Home 13 | 14 | {% if displayErrorDetails %} 15 |
    16 |
    17 |

    Exception: {{ name }}

    18 |
    Message: {{ message }}
    19 | {% if details %} 20 |
    {{ dump(details) }}
    21 | {% endif %} 22 |
    {{ stackTrace }}
    23 |
    24 | {% endif %} 25 |
    26 |
    27 | {% endblock %} 28 | -------------------------------------------------------------------------------- /templates/index.html.twig: -------------------------------------------------------------------------------- 1 | {% extends 'layouts/base.html.twig' %} 2 | 3 | {% block title %}Url's um tanto pequenas e grátis{% endblock %} 4 | 5 | {% block content %} 6 |
    7 | 10 |
    11 |
    12 |
    13 |
    14 |
    15 | 16 | 17 |
    18 |
    19 |
    20 |
    21 |
    22 |
    23 | 26 |
    27 |
    28 |
    29 |
    30 |
    31 | 32 |   33 |   34 | 35 | 38 | 41 |
    42 |
    43 |
    44 | 45 |

    Mais de {{ totalUrls }} URL's encurtadas e mais de {{ totalClicks }} cliques.

    46 |
    47 |
    48 |
    49 |
    50 | 53 |
    54 |
      55 |
      56 |
      57 |
      58 |
      59 |
      60 | {% endblock %} 61 | -------------------------------------------------------------------------------- /templates/layouts/_messages.html.twig: -------------------------------------------------------------------------------- 1 | {% for message in flash.getMessage('success') %} 2 | 7 | {% endfor %} 8 | 9 | {% for message in flash.getMessage('error') %} 10 | 15 | {% endfor %} 16 | -------------------------------------------------------------------------------- /templates/layouts/base.html.twig: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | {% block styles %}{% endblock %} 36 | 37 | 41 | 42 | 45 | {% block headScripts %}{% endblock %} 46 | 47 | Smallish | {% block title %}{% endblock %} 48 | 49 | 50 | 51 | 58 | 59 | 60 | {% include 'layouts/_messages.html.twig' %} 61 |
      62 |
      63 | 64 | GitHub forks 65 | 66 | 67 | GitHub Repo stars 68 | 69 |
      70 | {% block content %}{% endblock %} 71 |
      72 | 73 | 74 | 75 | 76 | 77 | {% block scripts %}{% endblock %} 78 | 79 | 80 | -------------------------------------------------------------------------------- /templates/layouts/blank.html.twig: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | {% block styles %}{% endblock %} 40 | 41 | 45 | 46 | {% block headScripts %}{% endblock %} 47 | 48 | {% block title %}{% endblock %} | Devtube Treinamentos 49 | 50 | 51 | 52 |
      53 | {% block content %}{% endblock %} 54 |
      55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | {% block scripts %}{% endblock %} 66 | 67 | 68 | -------------------------------------------------------------------------------- /templates/notfound.html.twig: -------------------------------------------------------------------------------- 1 | {% extends 'layouts/base.html.twig' %} 2 | 3 | {% block title %}URL não foi encontrada{% endblock %} 4 | 5 | {% block content %} 6 |
      7 | 10 |
      11 |

      Desculpe... mas a URL que você informou não foi encontrada =(.

      12 | Encurtar uma URL 13 |
      14 |
      15 | {% endblock %} 16 | -------------------------------------------------------------------------------- /tests/Integration/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dersonsena/small-sh/bfb1596789ac6966318f47b1d9f0bbde0e49545a/tests/Integration/.gitkeep -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | 2 | 15 | 16 | 17 | ../src 18 | 19 | 20 | 21 | 22 | Unit 23 | 24 | 25 | Integration 26 | 27 | 28 | 29 | --------------------------------------------------------------------------------