Skip to content

Commit

Permalink
Merge pull request #1 from hellofresh/feature/initial-version
Browse files Browse the repository at this point in the history
Initial version
  • Loading branch information
vgarvardt authored Oct 24, 2017
2 parents 8c4b32c + 6a24af6 commit 54955b7
Show file tree
Hide file tree
Showing 59 changed files with 2,822 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/*
composer.lock
.php_cs.cache
38 changes: 38 additions & 0 deletions .php_cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

$finder = PhpCsFixer\Finder::create()
->exclude('vendor')
->in(__DIR__);

return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],

'blank_line_after_namespace' => true,
'blank_line_before_return' => true,
'concat_space' => ['spacing' => 'one'],
'function_typehint_space' => true,
'hash_to_slash_comment' => true,
'include' => true,
'lowercase_cast' => true,
'new_with_braces' => true,
'no_blank_lines_before_namespace' => true,
'no_empty_statement' => true,
'no_extra_consecutive_blank_lines' => ['use'],
'no_leading_import_slash' => true,
'no_unused_imports' => true,
'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
'phpdoc_align' => true,
'phpdoc_scalar' => true,
'phpdoc_types' => true,
'short_scalar_cast' => true,
'single_blank_line_at_eof' => true,
'single_quote' => true,
'trailing_comma_in_multiline_array' => true,
'ordered_imports' => true,
'phpdoc_order' => true,
])
->setFinder($finder);
18 changes: 18 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
language: php

php:
- '5.6'
- '7.0'
- '7.1'

env:
- COMPOSER_UPDATE=
- COMPOSER_UPDATE=--prefer-lowest

script:
- composer update $COMPOSER_UPDATE -n
- vendor/bin/php-cs-fixer fix --dry-run -v
- vendor/bin/phpunit --coverage-clover=coverage.xml

after_success:
- if [ "$TRAVIS_SECURE_ENV_VARS" == "true" ]; then bash <(curl -s https://codecov.io/bash); fi
46 changes: 46 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [[email protected]](mailto:[email protected]). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
65 changes: 65 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Contributing to hellofresh/stats-php

:+1::tada: First off, thanks for taking the time to contribute! :tada::+1:

The following is a set of guidelines for contributing to `hellofresh/stats-php`,
which are hosted in the [HelloFresh Organization](https://github.com/hellofresh) on GitHub.
These are just guidelines, not rules. Use your best judgment, and feel free to propose changes
to this document in a pull request.

## Code of Conduct

This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code.
Please report unacceptable behavior to [[email protected]](mailto:[email protected]).

We accept contributions via Pull Requests on [Github](https://github.com/hellofresh/stats-php).

## How Can I Contribute?

### Reporting Bugs

This section guides you through submitting a bug report for `hellofresh/stats-php`. Following these guidelines helps maintainers
and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related
reports :mag_right:.

Before creating bug reports, please check if the bug was already reported before as you might find out that you don't
need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report).

#### How Do I Submit A (Good) Bug Report?

Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue on provide the following information.

Explain the problem and include additional details to help maintainers reproduce the problem:

* **Use a clear and descriptive title** for the issue to identify the problem.
* **Describe the exact steps which reproduce the problem** in as many details as possible. For example, start by explaining how you started `hellofresh/stats-php`,
e.g. which command exactly you used in the terminal. When listing steps, **don't just say what you did, but explain how you did it**.
* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples.
If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
* **Explain which behavior you expected to see instead and why.**

Include details about your configuration and environment:

* **Which version of `hellofresh/stats-php` are you using?**
* **What's the name and version of the OS you're using**?

### Your First Code Contribution

Unsure where to begin contributing to `hellofresh/stats-php`? You can start by looking through these `beginner` and `help-wanted` issues:

* [Beginner issues][beginner] - issues which should only require a few lines of code, and a test or two.
* [Help wanted issues][help-wanted] - issues which should be a bit more involved than `beginner` issues.

Both issue lists are sorted by total number of comments. While not perfect, number of comments is a reasonable proxy for impact a given change will have.

### Pull Requests

* Include screenshots and animated GIFs in your pull request whenever possible.
* Include thoughtfully-worded, well-structured tests.
* Document new code
* End files with a newline.


Happy Coding from the HelloFresh Engineering team!
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 HelloFresh SE <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
95 changes: 95 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<p align="center">
<a href="https://hellofresh.com">
<img width="120" src="https://www.hellofresh.de/images/hellofresh/press/HelloFresh_Logo.png">
</a>
</p>

# hellofresh/stats-php

[![Build Status](https://travis-ci.org/hellofresh/stats-php.svg?branch=master)](https://travis-ci.org/hellofresh/stats-php)
[![codecov](https://codecov.io/gh/hellofresh/stats-php/branch/master/graph/badge.svg)](https://codecov.io/gh/hellofresh/stats-php)

> Generic Stats library written in PHP
This is generic stats library that we at HelloFresh use in our projects to collect services' stats and then create monitoring
dashboards to track activity and problems.

## Key Features

* Several stats backends:
* `log` for development environment
* `statsd` for production
* `memory` for testing purpose, to track stats operations in unit tests
* `noop` for environments that do not require any stats gathering
* Fixed metric sections count for all metrics to allow easy monitoring/alerting setup in `grafana`
* Easy to build HTTP requests metrics - timing and count

## Installation

```sh
composer require hellofresh/stats-php
```

## Usage

### Instance creation

Connection DSN has the following format: `<type>://<connection params>/<connection path>?<connection options>`.

* `<type>` - one of supported backends: `log`, `statsd`, `memory`, `noop`
* `<connection params>` - used for `statsd` backend only, to defining host and port
* `<connection path>` - used for `statsd` backend only, to define prefix/namespace
* `<connection options>` - user for `statsd` backend only:
* `timeout` - statsd request timeout in seconds, if not set `ini_get('default_socket_timeout')` is used
* `error` - throw connection error exception, default value is `true`

```php
<?php

use HelloFresh\Stats\Factory;

$statsdClient = Factory::build('statsd://statsd-host:8125/prefix?timeout=2.5&error=1', $logger);

// php parse_url does not support url with only schema part set
$logClient = Factory::build('log://log', $logger);

// php parse_url does not support url with only schema part set
$noopClient = Factory::build('noop://noop', $logger);

// php parse_url does not support url with only schema part set
$memoryClient = Factory::build('memory://memory', $logger);

// php parse_url does not support url with only schema part set
$statsClient = Factory::build(getenv('STATS_DSN'), $logger);
```

### Count metrics manually

```php
<?php

use HelloFresh\Stats\Bucket\MetricOperation;
use HelloFresh\Stats\Factory;

$statsClient = Factory::build(getenv('STATS_DSN'), $logger);

$section = 'ordering';
$timer = $statsClient->buildTimer()->start();
$operation = new MetricOperation(['orders', 'order', 'create']);

try {
OrdersService::create(...);
$statsClient->trackOperation($section, $operation, true, $timer);
} catch (\Exception $e) {
$statsClient->trackOperation($section, $operation, false, $timer);
}

$statsClient->trackMetric('requests', $operation);

$ordersInTheLast24Hours = OrdersService::count(60 * 60 * 24);
$statsClient->trackState($section, $operation, $ordersInTheLast24Hours);
```

## TODO

* [ ] Generalise or modify HTTP Requests metric - e.g. skip ID part
37 changes: 37 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "hellofresh/stats-php",
"keywords": [
"logging",
"stats"
],
"homepage": "https://github.com/hellofresh/stats-php",
"license": "MIT",
"authors": [
{
"name": "Vladimir Garvardt",
"email": "[email protected]"
}
],
"support": {
"email": "[email protected]"
},
"autoload": {
"psr-4": {
"HelloFresh\\Stats\\": "src/"
}
},
"require": {
"php": ">= 5.6",
"psr/http-message": "^1.0",
"behat/transliterator": "^1.2",
"psr/log": "^1.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.3",
"phpunit/phpunit": "^5.7",
"league/statsd": "^1.4"
},
"suggest": {
"league/statsd": "Required for statsd backend"
}
}
6 changes: 6 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: '3'
services:
app:
image: quay.io/hellofresh/php56
volumes:
- ".:/app"
29 changes: 29 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="true"
stopOnFailure="false"
syntaxCheck="false"
verbose="true"
>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
</logging>

<testsuites>
<testsuite name="main">
<directory>./tests/</directory>
</testsuite>
</testsuites>

<filter>
<whitelist>
<directory>./src</directory>
</whitelist>
</filter>
</phpunit>
Loading

0 comments on commit 54955b7

Please sign in to comment.