Skip to content

Commit

Permalink
Merge pull request #20 from codex-team/hawk-2.0
Browse files Browse the repository at this point in the history
Hawk 2.0
  • Loading branch information
khaydarov authored Apr 5, 2021
2 parents 5ca2150 + 8e8787a commit 18cdaf6
Show file tree
Hide file tree
Showing 25 changed files with 1,351 additions and 719 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ composer.lock
vendor/
.idea/
.DS_Store
.phpunit.result.cache
44 changes: 44 additions & 0 deletions .php_cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php
return PhpCsFixer\Config::create()
->setUsingCache(false)
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => ['align_double_arrow' => true],
'blank_line_before_return' => true,
'cast_spaces' => true,
'concat_space' => ['spacing' => 'one'],
'declare_equal_normalize' => true,
'line_ending' => false,
'method_argument_space' => true,
'method_separation' => true,
'no_blank_lines_before_namespace' => false,
'no_empty_statement' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_multiline_whitespace_around_double_arrow' => true,
'no_multiline_whitespace_before_semicolons' => true,
'no_trailing_comma_in_list_call' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_unused_imports' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'ordered_imports' => true,
'phpdoc_add_missing_param_annotation' => true,
'phpdoc_align' => true,
'phpdoc_indent' => true,
'phpdoc_no_empty_return' => false,
'phpdoc_order' => false,
'phpdoc_separation' => true,
'phpdoc_scalar' => true,
'return_type_declaration' => true,
'short_scalar_cast' => true,
'single_import_per_statement' => false,
'single_quote' => true,
'ternary_operator_spaces' => true,
'trim_array_spaces' => true,
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__)
);
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2018 CodeX
Copyright (c) 2021 CodeX

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
107 changes: 24 additions & 83 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,117 +2,58 @@

PHP errors Catcher for [Hawk.so](https://hawk.so).

![](https://capella.pics/c0fe5eeb-027d-427a-9e0d-b2e1dcaaf303)
![](https://capella.pics/image/4c6e5fee-da7e-4bc5-a898-f19d12acb005)

## Usage
## Setup

1. [Register](https://hawk.so/join) an account and get an Integration Token.
1. [Register](https://hawk.so/join) an account and get Integration Token.

2. Install module

Use [composer](https://getcomposer.org) to install Catcher
2. Install SDK via [composer](https://getcomposer.org) to install Catcher

```bash
$ composer require codex-team/hawk.php
```

3. Use as a [standalone catcher](#standalone-error-catcher) or use with [Monolog](#monolog-support).

## Standalone error catcher

Create an instance with Token at the entry point of your project.

```php
\Hawk\HawkCatcher::instance('abcd1234-1234-abcd-1234-123456abcdef');
```

### Enable handlers

By default Hawk will catch everything. You can run function with no params.

```php
\Hawk\HawkCatcher::enableHandlers();
```

It's similar to
### Configuration

```php
\Hawk\HawkCatcher::enableHandlers(
TRUE, // exceptions
TRUE, // errors
TRUE // shutdown
);
\Hawk\Catcher::init([
'integrationToken' => 'your integration token'
]);
```

You can pass types of errors you want to track:
After initialization you can set `user` or `context` for any event that will be send to Hawk

```php
// Catch run-time warnings or compile-time parse errors
\Hawk\HawkCatcher::enableHandlers(
TRUE, // exceptions
E_WARNING | E_PARSE, // errors
TRUE // shutdown
);
\Hawk\Catcher::get()
->setUser([
'name' => 'user name',
'photo' => 'user photo',
])
->setContext([
...
]);
```

```php
// Catch everything except notices
\Hawk\HawkCatcher::enableHandlers(
TRUE, // exceptions
E_ALL & ~E_NOTICE, // errors
TRUE // shutdown
);
```

### Catch handled exceptions
### Send events and exceptions manually

You can catch exceptions manually with `catchException` method.
Use `sendException` method to send any caught exception

```php
try {
throw new Exception("Error Processing Request", 1);
} catch (Exception $e) {
\Hawk\HawkCatcher::catchException($e);
}
```

## Monolog support

Add a handler to the Monolog. It will catch errors/exception and ignore general logs.

```php
$logger = new \Monolog\Logger('hawk-test');

$HAWK_TOKEN = 'abcd1234-1234-abcd-1234-123456abcdef';
$logger->pushHandler(new \Hawk\Monolog\Handler($HAWK_TOKEN, \Monolog\Logger::DEBUG));
```

Now you can use logger's functions to process handled exceptions. Pass it to context array in 'exception' field.

```php
try {
throw new Exception('Something went wrong');
} catch (\Exception $e) {
$logger->error($e->getMessage(), ['exception' => $e]);
\Hawk\Catcher::get()->sendException($e);
}
```

### Default error catcher

Register Monolog's handler as catcher.

```php
/** Set monolog as default error handler */
$handler = \Monolog\ErrorHandler::register($logger);
```

It catches all errors and sends them to Hawk.

Throwing unhandled error example (without try-catch construction):
Use `sendEvent` method to send any data (logs, notices or something else)

```php
/** Fatal Error: "Just an error in a high quality code" */
throw new Error('Just an error in a high quality code', E_USER_ERROR);
\Hawk\Catcher::get()->sendMessage('your message', [
... // Context
]);
```

## Issues and improvements
Expand Down
26 changes: 21 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
{
"name": "codex-team/hawk.php",
"description": "PHP errors Catcher module for Hawk.so",
"keywords": ["hawk", "php", "error", "catcher", "monolog"],
"type": "library",
"version": "2.0.0",
"license": "MIT",
"require": {
"ext-curl": "*",
"php": ">=5.3"
"ext-json": "*",
"php": "^7.1"
},
"require-dev": {
"phpunit/phpunit": "^8.2",
"friendsofphp/php-cs-fixer": "^2.15",
"symfony/var-dumper": "^5.2"
},
"autoload": {
"classmap": [
"src/Hawk.php"
],
"psr-4": {"Hawk\\": "src/"}
"psr-4": {
"Hawk\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Hawk\\Tests\\": "tests/"
}
},
"scripts": {
"test": "vendor/bin/phpunit --testdox",
"csfix": "vendor/bin/php-cs-fixer fix --config=.php_cs --verbose"
}
}
20 changes: 20 additions & 0 deletions example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/**
* To run this example script
*
* 1. Update integrationToken
* 2. Ignore url to use production collector
* 3. Install composer deps: composer install
* 4. Run the script: php -e example.php
*/

require_once './vendor/autoload.php';

\Hawk\Catcher::init([
'integrationToken' => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9qZWN0SWQiOiI2MDY2ZWI5N2U3NTU2ZDAwMjM2M2UyNjYiLCJpYXQiOjE2MTczNTc3MTl9.OpelHPPvS_TB8wUqCHRzcO3-Cp1VNL0UzlFuMfR35tk',
'release' => '12345',
'url' => 'http://localhost:3000/'
]);

$a = 1 / 0;
23 changes: 23 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutOutputDuringTests="true"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
failOnRisky="true"
failOnWarning="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
verbose="true"
>
<testsuites>
<testsuite name="Hawk PHP catcher suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
</phpunit>
20 changes: 20 additions & 0 deletions src/Addons/AddonInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Hawk\Addons;

/**
* Interface Addon
*
* @package Hawk\Addons
*/
interface AddonInterface
{
/**
* Returns addon extra data
*
* @return array
*/
public function resolve(): array;
}
43 changes: 43 additions & 0 deletions src/Addons/Headers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace Hawk\Addons;

/**
* Class Headers
*
* @package Hawk\Addons
*/
class Headers implements AddonInterface
{
/**
* @var string[]
*/
private $fields = [
'DOCUMENT_ROOT',
'REMOTE_ADDR',
'REMOTE_PORT',
'SERVER_PROTOCOL',
'SERVER_NAME',
'SERVER_PORT',
'HTTP_CONNECTION',
'HTTP_CACHE_CONTROL',
'HTTP_USER_AGENT',
'HTTP_ACCEPT',
'QUERY_STRING'
];

/**
* @inheritDoc
*/
public function resolve(): array
{
$result = [];
foreach ($this->fields as $field) {
$result[$field] = $_SERVER[$field] ?? '';
}

return $result;
}
}
26 changes: 26 additions & 0 deletions src/Addons/Os.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Hawk\Addons;

/**
* Class Os
*
* @package Hawk\Addons
*/
class Os implements AddonInterface
{
/**
* @inheritDoc
*/
public function resolve(): array
{
return [
'name' => php_uname('s'),
'version' => php_uname('r'),
'build' => php_uname('v'),
'kernel_version' => php_uname('a'),
];
}
}
Loading

0 comments on commit 18cdaf6

Please sign in to comment.